Given an integer n, return 1 through n in lexicographical order.
Input: n = 13
Output: [1,10,11,12,13,2,3,4,5,6,7,8,9]
Input: n = 2
Output: [1,2]
n?
1 <= n <= 5000 is reasonable unless specified otherwise.n?
n is always a positive integer according to the problem.n and then sort them lexicographically.1 to 9.1 to 9.
0 to 9 as the next digit unless it exceeds n.O(n) since each number from 1 to n is processed exactly once.O(n) for storing the result.Here is the Python implementation of the described approach:
def lexicalOrder(n: int) -> list:
def dfs(current):
if current > n:
return
result.append(current)
for i in range(10):
if 10 * current + i <= n:
dfs(10 * current + i)
else:
break
result = []
for i in range(1, 10):
dfs(i)
return result
# Example Usage
n = 13
print(lexicalOrder(n)) # Output: [1,10,11,12,13,2,3,4,5,6,7,8,9]
This code will generate the lexicographical order of numbers from 1 to n by using DFS starting from each number 1 through 9 and recursively building upon those.
This approach ensures that the numbers are naturally constructed in lexicographical order without needing an extra sort step, providing an efficient solution.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?