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.

Constraints

  • 1 โ‰ค n โ‰ค 5 ร— 104
  • Must run in O(n) time complexity
  • Must use O(1) extra space (excluding output array)

Visualization

Tap to expand
Lexicographical Numbers as 10-ary TreeRoot123...101112DFS Traversal Path (n=13)Step-by-Step:1. Start at 1 โ†’ Add to result: [1]2. Go deep: 1ร—10=10 โ†’ Add: [1,10]3. Go deep: 10ร—10=100 > 13, try sibling: 10+1=11 โ†’ Add: [1,10,11]4. Continue siblings: 11โ†’12โ†’13 โ†’ Result: [1,10,11,12,13]5. 13+1=14 > 13, backtrack: 13รท10=1, then 1+1=2 โ†’ Add: [1,10,11,12,13,2]6. Continue: 2โ†’3โ†’4โ†’5โ†’6โ†’7โ†’8โ†’9 โ†’ Final: [1,10,11,12,13,2,3,4,5,6,7,8,9]๐ŸŽฏ Key InsightDFS on a conceptual 10-ary tree naturally produces lexicographical order - no sorting needed!
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.
Asked in
Google 35 Amazon 28 Facebook 22 Microsoft 18
67.2K Views
Medium Frequency
~15 min Avg. Time
1.8K 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