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
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
⚡ Linearithmic
Space Complexity
O(n)
Need to store all n numbers as strings
⚡ 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
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code