Problem
Given an integer n, return all the numbers in the range [1, n] sorted in lexicographical order.
You must write an algorithm that runs in O(n) time and uses O(1) extra space.
Examples
Example 1:
| |
Example 2:
| |
Solution
Video Explanation
Video explanation
Here is the video explaining this method in detail. Please check it out:
Method 1 - DFS
Using DFS in a preorder manner(i.e. add the result as soon as we find it and then process the children) to generate numbers in lexicographical order:
- Start from the number
1. - Recursively try to go deeper (multiplying by 10) to maintain the smallest lexical order.
- If multiplying is not possible, i.e. number exceed n, we backtrack , and consider the next number (increment), and go to siblings
- Continue this process until all numbers are processed.
For eg.. number 133, here is how the dfs tree:
graph TD
A["Start"]
A --> B1["1"]
A --> B2["2"]
A --> B3["..."]
A --> B4["9"]
B1 --> C1["10"]
B1 --> C2["11"]
B1 --> C3["12"]
B1 --> C4["13"]
B1 --> C5["..."]
B1 --> C6["19"]
C1 --> D1["100"]
C1 --> D2["101"]
C1 --> D3["..."]
C1 --> D4["109"]
D1 ---> E1["1000"]
C2 --> F1["110"]
C2 --> F2["111"]
C2 --> F3["..."]
C2 --> F4["119"]
C3 --> G1["120"]
C3 --> G2["..."]
C4 --> G3["130"]
C4 --> G4["131"]
C4 --> G5["132"]
C4 --> G6["133"]
E1:::red
classDef red fill:#f96,stroke:#333,stroke-width:2px;
Code
| |
| |
Complexity
- ⏰ Time complexity:
O(n), because we generate and process each number exactly once. - 🧺 Space complexity:
O(1)- Typical recursion depth in the worst case can be (O(\log_{10} n)), but this is not considered extra space complexity based on the problem constraints.
Method 2 - Iterative
To generate numbers in lexicographical order from 1 to n, we simulate the process of numbering in dictionary order by:
- Initializing the curr number as
1. - Attempting to multiply the
currentnumber by10if possible to maintain the smallest lexical order. - Incrementing the number when multiplying results in a value greater than
n. - Handling cases where the incremented number results need adjusting to valid lexicographical numbers.
Code
| |
| |
Complexity
- ⏰ Time complexity:
O(n) - 🧺 Space complexity:
O(1)