440. K-th Smallest in Lexicographical Order
Description
Given integers n
and k
, find the lexicographically k-th smallest integer in the range from 1
to n
.
Note: 1 ≤ k ≤ n ≤ 109.
Example:
Tags
Tree
Solution
In essential, we can build a 10-ary tree to represent a set of number from 1 to n in Lexicographical Order. We can obtain the k-th number by moving a pointer cur
from 1 with k-1
steps in pre-order manner. To jump over a bunch of nodes, we can check if the k-th number is belonging the child of cur
. To achieve this, we calculate the number of nodes (which should not be greater than n
) and compare it with k
. If the number is smaller than k
, we substract these nodes from k
and move cur
by 1 step horizontally. Otherwise, we let k--
and cur*=10
, which means we dive into the next level and find the k-th number on this level. When k==0
, we return cur
.
Complexity
Time complexity:
Space complexity:
Code
Reference
Last updated
Was this helpful?