Problem
Give integers n and k, list all numbers from 1 n in directory order, then return $k^{th}$ number in that list.
Logic
Intuitively, we can generate all numbers $[1..n]$, convert to string, sort, resulting to an $O(O log n)$.
Brutely, we can have the following code.
1 | class Solution { |
No surprise, Time Limit Exceeded.
The directory sequence corresponds to a 10-ary prefix tree of numbers. Each node x
has children x0, x1,...,x9
(of course if it still <=n ).
We can count how many nodes are in each subtree and skip entire subtree when their size < k.
we can have following solution.
1 | class Solution { |
countStep will calculate how many numbers exist with a prefix between ‘curr’ and ‘next’, and it should be <=n.
1 | static long countSteps(long long curr, long long next, long n){ |