Find the k-th smallest integer from 1 to n in lexicographical order
Company: ByteDance
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: hard
Interview Round: Other
Overview: Given n and k, find the k-th integer in the range 1 to n when the numbers are ordered as decimal strings in dictionary order. Since n can be as large as one billion, it tests reasoning about the structure of that order and counting numbers without listing them.
Constraints
- 1 <= n <= 10^9
- 1 <= k <= n
Examples
Input: (1, 1)
Expected Output: 1
Explanation: Minimum valid input: the range holds only 1.
Input: (13, 2)
Expected Output: 10
Explanation: Source example: the order is 1, 10, 11, 12, 13, 2, ..., 9, so the 2nd number is 10.
Hints
- Writing out all n numbers and sorting them as strings is correct for small n, but n can be as large as 10^9.
- In the second example, the 12 numbers that start with the digit 1 all come before 2. Knowing how many numbers in [1, n] begin with a given digit string tells you how many positions that whole group takes up.
- Check boundary cases by hand: n equal to a power of ten such as 10 or 100, and k equal to n.