Lexicographical Numbers — LeetCode 386 Python Solution

MediumDepth-First SearchTrie
Problem
#386
Pattern
Trie
Reading time
2 min

The problem

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

Input
n = 13
Output
[1,10,11,12,13,2,3,4,5,6,7,8,9]

Python solution

Python
class Solution:
    def lexicalOrder(self, n: int) -> List[int]:
        ans = []
        v = 1
        for _ in range(n):
            ans.append(v)
            if v * 10 <= n:
                v *= 10
            else:
                while v % 10 == 9 or v + 1 > n:
                    v //= 10
                v += 1
        return ans

Complexity

MeasureComplexity
TimeO(n), where n is the given integer n
SpaceO(1) auxiliary

Pattern: Trie

Store a set of words by their shared prefixes so lookups cost the length of the word. LeetCode 386. Lexicographical Numbers is filed here because LeetCode tags it Trie, which is the vocabulary this hub collects.

The trie guide has the Python template for the pattern and the 49 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 386. Lexicographical Numbers?
LeetCode 386. Lexicographical Numbers is rated Medium on LeetCode.
What is the time complexity of LeetCode 386. Lexicographical Numbers?
The Python solution on this page runs in O(n), where n is the given integer n.
What is the space complexity of LeetCode 386. Lexicographical Numbers?
The Python solution on this page uses O(1) auxiliary space.
What topics does LeetCode 386. Lexicographical Numbers cover?
LeetCode 386. Lexicographical Numbers is tagged Depth-First Search and Trie on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview