Ctrl K

K-th Number in Dictionary Order

Hard
Write down every integer from 1 to limit and sort them as strings, the way words are sorted in a dictionary: compare the first digit, then the second, and so on, with a shorter number coming first when it is the start of a longer one. For example, 1 < 10 < 100 < 11 < 2. Return the number that ends up in position k (counting from 1). Listing everything will not work: limit can be as large as a billion.
Example 1
limit=15, k=4 → 12

In dictionary order the numbers 1 to 15 go 1, 10, 11, 12, 13, 14, 15, 2, 3, … The fourth one is 12.

Example 2
limit=20, k=13 → 20

The order is 1, 10, …, 19, 2, 20, 3, …, so the thirteenth number is 20.

Example 3
limit=7, k=7 → 7
Constraints
  • 1 ≤ k ≤ limit ≤ 10⁹
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsEvery Way to Space the Words HardWords Hidden in a Letter Grid HardGlued Into a Palindrome HardMirror Word Blocks HardWords Built From Shorter Words Hard
loading Python…
Input
limit=15, k=4
Expected
12

Run checks the first 3 tests in your browser. Submit checks all 94 tests on the server, hidden ones included.