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
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
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code