Lexicographical Numbers - Problem

Given an integer n, return all the numbers in the range [1, n] sorted in lexicographical order.

Lexicographical order means the numbers are sorted as if they were strings. For example, [1, 10, 11, 2, 3] would be the lexicographical order for numbers 1-11.

Constraints: You must write an algorithm that runs in O(n) time and uses O(1) extra space.

Input & Output

Example 1 — Basic Case
$ Input: n = 13
Output: [1,10,11,12,13,2,3,4,5,6,7,8,9]
💡 Note: Numbers 1-13 in lexicographical order: 1 comes first, then 10,11,12,13 (all start with '1'), then 2,3,4,5,6,7,8,9
Example 2 — Small Range
$ Input: n = 2
Output: [1,2]
💡 Note: Only two numbers: 1 and 2, already in lexicographical order
Example 3 — Powers of 10
$ Input: n = 100
Output: [1,10,100,11,12,13,...,19,2,20,21,...,99]
💡 Note: Starts with 1, then all numbers beginning with '1' (10,100,11,12...19), then numbers starting with '2', etc.

Constraints

  • 1 ≤ n ≤ 5 × 104

Visualization

Tap to expand
Lexicographical Numbers: Dictionary Ordering (n=13)Input Range [1,13]Lexicographical Order1,2,3,4,5,6,7,8,9,10,11,12,131,10,11,12,13,2,3,4,5,6,7,8,9Normal numerical orderSorted as strings: "1" < "10" < "11" < "2"Why "10" comes before "2"?Compare character by character: "1" vs "2" → "1" < "2"So "10", "11", "12", "13" all come before "2"Result: [1,10,11,12,13,2,3,4,5,6,7,8,9]
Understanding the Visualization
1
Input
Range [1, n] where n=13
2
Process
Sort as if numbers were strings
3
Output
Numbers in dictionary order
Key Takeaway
🎯 Key Insight: Numbers form a tree structure where DFS traversal naturally produces lexicographical order
Asked in
Google 25 Amazon 20 Facebook 15 Microsoft 12
28.0K Views
Medium Frequency
~25 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