#386
Lexicographical Numbers
MediumDepth-First SearchTrieDepth-First SearchBacktracking
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n)Space O(1)
The optimal approach uses a depth-first search (DFS) strategy to generate numbers in lexicographical order without needing to sort them afterwards. This is efficient and meets the space requirements.
⚙️
Algorithm
5 steps- 1Step 1: Start with an empty list to hold the result.
- 2Step 2: Define a recursive function that takes the current number and builds the next number in lexicographical order.
- 3Step 3: For each number, append it to the result if it is less than or equal to n.
- 4Step 4: Multiply the current number by 10 to go deeper (e.g., from 1 to 10) and repeat.
- 5Step 5: If the current number is greater than n, return.
solution.py14 lines
1def lexicalOrder(n):
2 result = []
3 def dfs(current):
4 if current > n:
5 return
6 result.append(current)
7 for i in range(10):
8 dfs(current * 10 + i)
9 for i in range(1, 10):
10 dfs(i)
11 return result
12
13# Example usage:
14print(lexicalOrder(13))ℹ
Complexity note: The time complexity is O(n) since we are generating each number once, and the space complexity is O(1) because we are not using any additional data structures that grow with n.
- 1Lexicographical order is similar to dictionary order.
- 2Using DFS allows us to explore numbers in the correct order without sorting.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.