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 Order INPUT Lexicographical Order (n=13): 1 10 k=2 11 12 13 2 3... Virtual Trie Structure: root 1 2 3 10 11 12 Input Values: n = 13, k = 2 ALGORITHM STEPS 1 Start at prefix 1 curr=1, k=2 (need 2nd number) 2 Count nodes in subtree count(1,2) = 5 (1,10,11,12,13) steps = 0 n1=1, n2=2: steps += min(14,2)-1=1 n1=10,n2=20: steps += 14-10=4 3 Compare steps vs k steps=5 >= k=2: Go deeper! 4 Navigate to child curr = curr * 10 = 10 k = k - 1 = 1 (counted node 1) k=1 reached! Return curr=10 10 is the 2nd lex number Path: root --> 1 --> 10 Time: O(log n)^2 FINAL RESULT The k-th lexicographically smallest: 10 Verification: Position 1: 1 Position 2: 10 OK Position 3: 11 Position 4: 12 Position 5: 13 Output: 10 Key Insight: Treat numbers as a virtual trie (prefix tree). Instead of building the trie, count nodes in subtrees mathematically. If the subtree has enough nodes (count >= k), go deeper (multiply by 10). Otherwise, move to next sibling. This achieves O((log n)^2) time instead of O(n) by skipping entire subtrees when counting. TutorialsPoint - K-th Smallest in Lexicographical Order | Trie Navigation (Optimal)
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