K-th Smallest in Lexicographical Order

HardMathtrie

Solve this the way you would in the interview: out loud, on a timer, with an AI interviewer asking follow-ups while you code. You get a scored report at the end.

Practice this as a mock interviewFree to start, no account needed

Problem

Write the integers 1, 2, ..., n as decimal strings and sort them in dictionary (lexicographical) order. Return the integer that ends up at position k (1-indexed). For n = 13 the order is 1, 10, 11, 12, 13, 2, 3, 4, 5, 6, 7, 8, 9. n can be as large as 10^9, so you cannot build or sort the list. Aim for roughly O(log(n)^2) time.

Examples

Input: n = 13, k = 2
Output: 10
The order starts 1, 10, 11, ..., so the second number is 10.
Input: n = 1, k = 1
Output: 1
Only one number exists.

Constraints

  • 1 <= k <= n <= 10^9

What the interviewer grades

A correct solution is one of five scores. The report also grades problem understanding (did you clarify inputs and edge cases before coding), problem solving, communication while you work, code quality, and testing. See a sample report, or read up on the pattern in the lessons.

More trie problems