Skip to content
Problem 386 · LeetCode 386(opens in a new tab)

Lexicographical Numbers

MediumDepth-first search

You are given a whole number n. List every number from 1 to n, ordered the way a dictionary would order them if each number were written out as a word made of digits.

So 1 comes first, then every number that starts with 1 (10, 100, 11, ...), then 2, and so on. Aim for O(n) time and O(1) extra memory beyond the output list.

Example 1

Input:  n = 25
Output: [1, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 2, 20, 21,
         22, 23, 24, 25, 3, 4, 5, 6, 7, 8, 9]
Why:    "19" sorts before "2", and "25" before "3"
2 more examples and the constraints

Example 2

Input:  n = 5
Output: [1, 2, 3, 4, 5]
Why:    with one digit, text order and number order agree

Example 3

Input:  n = 1
Output: [1]
Why:    a single number

Constraints

  • 1 ≤ n ≤ 50,000

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. Sort as stringsO(n log n)
  2. DFS over the digit treeO(n)
  3. Step to the next numberO(n)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work for n = 50,000Verdict
Sort as stringsO(n log n)
Mention it, then move on
DFS over the digit treeO(n)
Passes; uses recursion
Step to the next numberO(n)
Best; O(1) extra space

n = the input number.

Edge cases to test

  • n below 10. n = 5 gives [1, 2, 3, 4, 5]: text order and number order agree.
  • n = 1. Just [1]. The climb loop must not run past it.
  • n is a power of 10. For n = 100, 100 comes right after 10.
  • Numbers ending in 9. After 19 comes 2, not 20: climb up, then add 1.

Common mistakes

  • Adding 1 after 19 to get 20, skipping the climb back up to 1 and on to 2.
  • Only checking cur % 10 == 9 and not cur + 1 > n, so numbers past n slip in.
  • Sorting numbers as numbers, which just gives 1 to n.

How to talk through it

  1. 1Clarify. Is the order the one you get by sorting the numbers as strings? Is O(n) time with O(1) extra space required?
  2. 2Give the simple version. Sort as strings, O(n log n), to fix the meaning.
  3. 3Draw the tree. Children of x are x × 10 to x × 10 + 9; preorder is dictionary order.
  4. 4Remove the stack. Go deeper with × 10; otherwise climb past 9s and the limit, then + 1.
  5. 5Test out loud. Run n = 1, n = 12 and n = 100 before saying you are done.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?