Lexicographical Numbers (LeetCode 386): Solution and Explanation

Medium
Depth First Search
Trie

Return 1..n in dictionary order. Instead of sorting strings, walk an imaginary trie where every number x has children x0 to x9, moving a single counter with three arithmetic rules.

Intuition

Dictionary order compares numbers digit by digit as strings, so 10, 11 and 12 all come before 2 because they start with 1.

That is exactly the order of a preorder traversal of a trie: the top level holds 1 to 9, and under each number x sit its children 10x to 10x + 9. Visit a node, then all of its children in order, then move on to its next sibling.

You never need the trie itself. Going to the first child is cur * 10, going to the next sibling is cur + 1, and going back to the parent is cur / 10. One integer is enough to walk the whole tree.

Approach: Iterative preorder with arithmetic moves

  1. Set cur = 1 and repeat n times.
  2. Append cur to the result.
  3. If cur * 10 <= n, cur has children, so go down: cur *= 10.
  4. Otherwise climb while cur is the last child (it ends in 9) or its next sibling would pass n (cur + 1 > n): cur //= 10.
  5. Then step to the next sibling with cur += 1.

Step-by-step example

n = 13
  1. Append 1. 1 * 10 = 10 is at most 13, so go down to 10.
  2. Append 10. 100 is too big, and 11 is at most 13, so move to the sibling 11. Append 11, then 12, then 13 the same way.
  3. After 13, 130 is too big and 14 is more than 13, so climb from 13 to 1. 1 does not end in 9 and 2 fits, so add 1 to get 2.
  4. Append 2. 20 is more than 13, so move to 3. The same happens for 3 through 8.
  5. Append 9. The loop has now run 13 times, giving [1,10,11,12,13,2,3,4,5,6,7,8,9].

Code: Python, Java, C++

1class Solution:
2    def lexicalOrder(self, n: int) -> List[int]:
3        res = []
4        cur = 1
5        for _ in range(n):
6            res.append(cur)
7            if cur * 10 <= n:
8                cur *= 10
9            else:
10                while cur % 10 == 9 or cur + 1 > n:
11                    cur //= 10
12                cur += 1
13        return res
Press play on the visualizer and the running line lights up here.

Time and space complexity

Work as the input growsinput size n →steps
Iterative preorder with arithmetic moves O(n)
Recursive DFS O(n)
Sort as strings O(n log n)
Time

O(n)

Each iteration appends one number. Climbs are paid for by the earlier steps down, so the total number of moves is O(n).

Space

O(1)

Only cur besides the output list.

Other approaches

Recursive DFS (time O(n), space O(log n))

For each first digit 1 to 9, recurse into x * 10 + d for d = 0..9 while the value stays at most n. Very readable, but the recursion stack is O(log n) deep.

Sort as strings (time O(n log n), space O(n))

Convert every number to a string and sort. Correct and short, but it costs O(n log n) time and O(n) extra space, which misses the stated limits.

Common mistakes

  • Only checking cur % 10 == 9 before climbing. If n is 13, the walk must also climb from 13 because 14 does not exist.
  • Using if instead of while for the climb. A number like 199 with n = 199 needs two climbs before the next sibling.
  • Running the loop until cur passes n instead of exactly n times. After the last number, the climb can drop cur to 0 and the next step brings it back to 1.
  • Sorting integers numerically by mistake. The order is by digits, so 10 must come before 2.

Frequently asked questions

Why is this a preorder traversal?

Comparing two numbers as strings looks at the first digit, then the second, and a shorter prefix comes first. In the trie, a parent is a prefix of its children, and preorder visits a parent before its children and children in digit order, which matches that rule.

Why is the climbing loop still O(n) overall?

Every divide by 10 undoes one earlier multiply by 10. There are at most n steps down, so there are at most n climbs in total.

Can cur become 0?

Only after the very last number has been appended, for example when n = 9 and cur climbs from 9. The loop has already run n times by then, so it never matters.