386. Lexicographical Numbers¶
Description¶
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.
Example 1
- Input: n = 13
- Output: [1,10,11,12,13,2,3,4,5,6,7,8,9]
Example 2
- Input: n = 2
- Output: [1,2]
Constraints
1 <= 5 <= 104
Solution: Iterative¶
First, we start from 1
and keep multiplying by 10
and incrementing by 1
until it exceeds n
. When it exceeds n
, we divide it by 10
and get the leading digits and increment it by 1
to get the next number.
- Time Complexity:
O(n)
,n
is the input number- Not
O(n2)
even thought it containswhile
insidefor
loop, becausewhile
is not dependent onn
and it bounds with10
at max which is constant. As long as it bounded by a constant or a small function (likeO(k)
for some constantk
), it still considered asO(n)
even though it might takes longer execution time.
- Space Complexity:
O(1)
Solution: Depth-First Search¶
We use trie1 or a prefix tree which . We can use trie to store the lexicographical order of numbers from 1
to n
.
- Time Complexity:
O(n)
,- We vist each node from
1
ton
once, therefore it depends on the number of nodes in the trie which is the input numbern
- We vist each node from
- Space Complexity:
O(log10(n))
- We store the numbers from
1
ton
in theresult
array which isO(n)
- We also have recursive call stack which depends on numbers from
1
ton
. Ifn
hasd
digits, the recursive call stack will beO(d)
which similar toO(log10(n))
- We store the numbers from