Problem
Given an integern, 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
Constraints
1 <= n <= 5 * 10^4
Documentation Index
Fetch the complete documentation index at: /llms.txt
Use this file to discover all available pages before exploring further.
Tested Python solution for LeetCode 386 with 12 pytest cases. Generate a practice environment with lcpy.
lcpy gen -n 386 # by problem number
lcpy gen -s lexicographical_numbers # by problem name
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.
Input: n = 13
Output: [1,10,11,12,13,2,3,4,5,6,7,8,9]
Input: n = 2
Output: [1,2]
1 <= n <= 5 * 10^4class Solution:
# Time: O(n)
# Space: O(1)
def lexical_order(self, n: int) -> list[int]:
result: list[int] = []
curr = 1
for _ in range(n):
result.append(curr)
if curr * 10 <= n:
curr *= 10
else:
while curr % 10 == 9 or curr + 1 > n:
curr //= 10
curr += 1
return result
| Time | Space |
|---|---|
| O(n) | O(1) |