Lexicographical Numbers

Given an integer n, return all the numbers in the range [1, n] sorted in lexicographical (dictionary) order. You must write an algorithm that runs in O(n) time and uses O(1) extra space.

30:00

Lexicographical Numbers
medium
Free written solution
Topics
Companies

Given an integer n, return all the numbers in the range [1, n] sorted in lexicographical (dictionary) 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]
Constraints:
  • 1≤n≤5×1041 \leq n \leq 5 \times 10^4

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"n":13}

List 1..13 in dictionary order, as if they were strings. Picture a trie: 1 to 9 at the top, and under every number x its children x0 to x9. Dictionary order is a preorder walk of that trie.

cur as a path from the root

start at 1
root
›

1

1

Trie, top two levels. Green = already in res.

1
10
11
12
13
2
3
4
5
6
7
8
9

res (0 of 13)

Variables
VariableValue
n13
cur1
count0
DepthFunction Call
Stack empty
0/28