K-th Smallest in Lexicographical Order - Problem

Given two integers n and k, return the k-th lexicographically smallest integer in the range [1, n].

Lexicographical order means dictionary order - numbers are compared digit by digit from left to right. For example: 1, 10, 11, 12, 2, 20, 21, 3, 30...

Note: This is different from numerical order where 2 comes before 10.

Input & Output

Example 1 — Basic Case
$ Input: n = 13, k = 2
Output: 10
💡 Note: Lexicographical order: 1, 10, 11, 12, 13, 2, 3, 4, 5, 6, 7, 8, 9. The 2nd element is 10.
Example 2 — First Element
$ Input: n = 1, k = 1
Output: 1
💡 Note: Only one number exists, so the 1st element is 1.
Example 3 — Larger Range
$ Input: n = 100, k = 10
Output: 17
💡 Note: Lexicographical order starts: 1, 10, 100, 11, 12, 13, 14, 15, 16, 17... The 10th element is 17.

Constraints

  • 1 ≤ k ≤ n ≤ 109

Visualization

Tap to expand
K-th Smallest in Lexicographical OrderInput: n = 13, k = 2Numbers 1 to 13: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]Lexicographical Order (like dictionary):1, 10, 11, 12, 13, 2, 3, 4, 5, 6, 7, 8, 9Find k=2nd element:11st102nd113rd124th...Answer: 10String "10" comes before "2" in dictionary order
Understanding the Visualization
1
Input
Range [1, n] and target position k
2
Process
Order numbers lexicographically like dictionary words
3
Output
Return the k-th number in this ordering
Key Takeaway
🎯 Key Insight: Lexicographical order treats numbers as strings, so "10" comes before "2" just like in a dictionary
Asked in
Google 25 Facebook 18 Amazon 15 Microsoft 12
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