Python 0386.py
class Solution:
def lexicalOrder(self, n: int) -> List[int]:
def deeper(start):
for i in range(start, start + 10):
if 0 < i <= n:
yield i
yield from deeper(i * 10)
yield from deeper(0)
Difficulty
and has an acceptance rate of about 73% (300k+ submissions).
Typical patterns to solve this problem:
- Depth First Search
- Trie
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The provided implementation defines a Solution class with a single method lexicalOrder. The method returns an iterator that produces the integers from 1 to n in lexical (dictionary) order. The core of the algorithm is a nested generator function named deeper that recursively explores the numeric tree formed by appending digits to a prefix. By yielding values directly from the generator, the solution avoids materialising the entire sequence in memory, which is especially beneficial for large values of n.
Key Steps
The algorithm can be broken down into three conceptual stages: the definition of the recursive generator, the iteration over possible digit extensions, and the initial invocation that starts the traversal.
Definition of the Recursive Generator
def deeper(start):
for i in range(start, start + 10):
if 0 < i <= n:
yield i
yield from deeper(i * 10)
In this snippet the function deeper receives a numeric prefix start. The for loop iterates over the ten possible next digits (including the current prefix itself). The conditional 0 < i <= n guarantees that only positive numbers within the target range are emitted. When a valid i is found, it is yielded immediately, and the generator recurses with the new prefix i * 10, thereby exploring all numbers that share i as a leading segment.
Iteration Over Digit Extensions
The loop for i in range(start, start + 10): systematically generates the sequence start, start+1, …, start+9. This deterministic progression mirrors the lexical ordering of numbers: after finishing all numbers that begin with a given prefix, the algorithm proceeds to the next sibling prefix. The recursion deeper(i * 10) dives deeper into the tree, producing numbers such as i0, i1, …, i9 before returning to the sibling level.
Initial Invocation
yield from deeper(0)
The method concludes by delegating to deeper with an initial prefix of 0. Because the conditional inside deeper excludes non-positive values, the first actual number emitted is 1. This entry point triggers the full depth-first traversal of the lexical tree, ultimately yielding every integer from 1 to n in the required order.
Edge Cases Handled
When n is zero, the condition 0 < i <= n never holds, so the generator produces no output. This behavior gracefully handles the empty range without raising errors.
If n is a single-digit number (for example, 5), the recursion deeper(i * 10) quickly reaches values that exceed n, and the guard clause prevents further descent, ensuring that only the numbers 1 through 5 are emitted.
For very large n, the recursion depth corresponds to the number of digits in the largest number, which is bounded by the length of n in decimal representation. The algorithm therefore remains safe from uncontrolled recursion depth growth.
Performance Optimizations
The solution leverages lazy evaluation through Python generators. By yielding each integer as soon as it is discovered, the algorithm avoids allocating a full list of size n. This reduces memory pressure and enables the caller to process the sequence incrementally.
The early cutoff if 0 < i <= n: acts as a pruning mechanism. As soon as a prefix exceeds n, the recursive call is never made, preventing unnecessary exploration of branches that cannot contribute valid numbers. This selective descent eliminates the overhead of generating and discarding out-of-range values.
The depth-first traversal aligns naturally with lexical ordering, removing the need for a separate sorting step. Consequently, the runtime work is limited to the generation of each valid number exactly once, without additional passes or auxiliary data structures.
ELI5 - Simplified Explanation
Imagine you have a big box of numbered blocks. This code acts like a helper who knows exactly which block to pick up next to keep them in a specific order, almost like how words are sorted in a dictionary.
Think of the process as starting at the very beginning and exploring a branching path. The code looks at a number and then tries to see if it can tuck even smaller numbers inside it, like opening a tiny door to find more numbers behind it. If the number is not too big, it picks that number up. Then it zooms in ten times larger to see if any more numbers are hiding just past that one.
It keeps going deeper and deeper, exploring every little path until it has found all the numbers up to the goal. By moving back and forth through these paths, all the numbers get lined up in the order the code wants, starting with one, then heading into the tens, then the hundreds, and so on. It is just like exploring a magical maze where every turn reveals the next number in the collection.
Code Quality
Complexity Analysis
As a rule of thumb, the maximum input size for one second execution time is
- factorial: up to 10 elements
- exponential: up to 20 elements
- polynomial: a few thousand elements
- loglinear: up to 100,000 elements
- linear: a few million elements
- logarithmic: a billion elements
- constant: practically unlimited
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | |||||||||
|---|---|---|---|---|---|---|---|---|---|
| author | solutions | ||||||||
| www | AlgoMonster | C++ | Java | Python | TS | ||||
| WalkCCC | C++ | Java | Python | ||||||
| leetcode.ca | C++ | JS | Java | Python | Go | Rust | TS | ||
| LeetcodeHelp | C++ | Java | Python | ||||||
| Progiez | C++ | Java | Python | ||||||
| github | black-shadows | C++ | |||||||
| charles-wangkai | Java | ||||||||
| everthis | JS | ||||||||
| halfrost | Go | ||||||||
| haoel | C++ | ||||||||
| JoshCrozier | JS | ||||||||
| linouk23 | C++ | ||||||||
| lkwq007 | Python | ||||||||
| lzl124631x | C++ | ||||||||
| suxrobGM | C# | ||||||||
| varunu28 | Java | ||||||||
| wisdompeak | C++ | ||||||||
| withaarzoo | C++ | ||||||||
| AlgoMonster | C++, Python, Java, TypeScript | ||||||||
| WalkCCC | C++, Python, Java | ||||||||
| leetcode.ca | C++, Go, Java, JavaScript, Python, Rust, TypeScript | ||||||||
| LeetcodeHelp | C++, Java, Python | ||||||||
| Progiez | C++, Java, Python | ||||||||
| black-shadows | C++, C++ | ||||||||
| charles-wangkai | Java | ||||||||
| everthis | JavaScript | ||||||||
| halfrost | Go | ||||||||
| haoel | C++ | ||||||||
| JoshCrozier | JavaScript | ||||||||
| linouk23 | C++ | ||||||||
| lkwq007 | Python | ||||||||
| lzl124631x | C++ | ||||||||
| suxrobGM | C# | ||||||||
| varunu28 | Java | ||||||||
| wisdompeak | C++ | ||||||||
| withaarzoo | C++ |
Videos
Solved On The Same Day
- problem 566: Reshape the Matrix
- problem 594: Longest Harmonious Subsequence
- problem 324: Wiggle Sort II
- problem 388: Longest Absolute File Path
- problem 390: Elimination Game
- problem 406: Queue Reconstruction by Height
- problem 491: Non-decreasing Subsequences
- problem 410: Split Array Largest Sum
- problem 472: Concatenated Words
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality