K-th Smallest in Lexicographical Order - Problem

Given two integers n and k, you need to find the k-th lexicographically smallest integer in the range [1, n].

Lexicographical order means dictionary order - where numbers are treated as strings and sorted alphabetically. For example, in lexicographical order: 1, 10, 11, 12, 2, 20, 21, 3, 30, 4, 5...

Example: If n = 13, the lexicographical order is: [1, 10, 11, 12, 13, 2, 3, 4, 5, 6, 7, 8, 9]

Your task is to return the k-th number from this ordered sequence efficiently, without generating all numbers.

Input & Output

example_1.py — Basic Case
$ Input: n = 13, k = 3
Output: 11
💡 Note: Lexicographical order: [1, 10, 11, 12, 13, 2, 3, 4, 5, 6, 7, 8, 9]. The 3rd number is 11.
example_2.py — Edge Case
$ Input: n = 1, k = 1
Output: 1
💡 Note: Only one number exists in range [1,1], so the 1st lexicographically smallest is 1.
example_3.py — Larger Range
$ Input: n = 100, k = 10
Output: 17
💡 Note: In lexicographical order: [1, 10, 100, 11, 12, 13, 14, 15, 16, 17, ...]. The 10th number is 17.

Visualization

Tap to expand
Smart Dictionary NavigationFinding k-th lexicographically smallest numberSection 1Numbers: 1, 10-19100-199, etc.Count: 1111Section 2Numbers: 2, 20-29200-299, etc.Count: 1111Section 3Numbers: 3, 30-39300-399, etc.Count: 1111...More sectionsDrill Down: Section 11101112If k=4, we found it!Skip count: 1+10+1=12Position 4 = number 12O((log n)²) Time Complexity
Understanding the Visualization
1
Index System
Like a dictionary index showing how many words start with each letter
2
Section Skipping
Skip entire sections when you know the target isn't there
3
Drill Down
Go deeper into subsections when you find the right area
4
Precise Location
Continue until you reach the exact k-th item
Key Takeaway
🎯 Key Insight: By treating numbers as a trie structure and calculating subtree sizes, we can navigate directly to the k-th position without generating intermediate values.

Time & Space Complexity

Time Complexity
⏱️
O(n log n)

O(n) to generate numbers + O(n log n) for sorting

n
2n
Linearithmic
Space Complexity
O(n)

Need to store all n numbers as strings

n
2n
Linearithmic Space

Constraints

  • 1 ≤ k ≤ n ≤ 109
  • k is guaranteed to be valid (within range [1, n])
  • The answer will fit in a 32-bit integer
Asked in
Google 45 Meta 32 Amazon 28 Microsoft 22
28.5K Views
Medium Frequency
~35 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen