Lexicographical Numbers - Problem
๐ค Lexicographical Numbers
Imagine you need to arrange numbers from 1 to n as if they were words in a dictionary! In lexicographical (dictionary) order, we compare numbers as strings character by character.
For example, with n = 13:
- Normal order:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13] - Lexicographical order:
[1, 10, 11, 12, 13, 2, 3, 4, 5, 6, 7, 8, 9]
Notice how 10 comes after 1 but before 2 because when comparing as strings, "10" starts with "1" and "0" comes before "2".
The challenge: You must solve this in O(n) time and use only O(1) extra space (excluding the output array)!
Input & Output
example_1.py โ Basic Case
$
Input:
n = 13
โบ
Output:
[1,10,11,12,13,2,3,4,5,6,7,8,9]
๐ก Note:
Numbers 1-13 arranged lexicographically. Notice how 10,11,12,13 all come after 1 but before 2, since they start with '1' when compared as strings.
example_2.py โ Single Digit
$
Input:
n = 5
โบ
Output:
[1,2,3,4,5]
๐ก Note:
When n โค 9, lexicographical order is the same as numerical order since all numbers are single digits.
example_3.py โ Larger Range
$
Input:
n = 25
โบ
Output:
[1,10,11,12,13,14,15,16,17,18,19,2,20,21,22,23,24,25,3,4,5,6,7,8,9]
๐ก Note:
With n=25, we see the full pattern: 1 followed by all numbers starting with 1 (10-19), then 2 followed by numbers starting with 2 (20-25), then remaining single digits.
Visualization
Tap to expand
Understanding the Visualization
1
Root Level
Start with digits 1-9 as root nodes
2
Branch Out
Each number can branch to 10 children by appending digits 0-9
3
DFS Traversal
Traverse depth-first: go as deep as possible before trying siblings
4
Natural Order
DFS order gives lexicographical order automatically!
Key Takeaway
๐ฏ Key Insight: By treating numbers as nodes in a 10-ary tree and performing DFS traversal, we get lexicographical order naturally without any sorting, achieving optimal O(n) time and O(1) space complexity.
Time & Space Complexity
Time Complexity
O(n)
We visit each number from 1 to n exactly once
โ Linear Growth
Space Complexity
O(1)
Only using a constant amount of extra variables (excluding output array)
โ Linear Space
Constraints
- 1 โค n โค 5 ร 104
- Must run in O(n) time complexity
- Must use O(1) extra space (excluding output array)
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code