Python 1291.py
class Solution:
def sequentialDigits(self, low: int, high: int) -> List[int]:
for digits in range(2, 10):
for start in range(9 - digits + 1):
check = int("123456789"[start:digits+start])
if low <= check <= high:
yield check
Difficulty
and has an acceptance rate of about 66% (300k+ submissions).
Typical patterns to solve this problem:
- Enumeration
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 Solution class implements a generator method sequentialDigits that produces all integers within a given inclusive range [low, high] whose decimal representation consists of consecutive increasing digits. The method leverages the fixed sequence "123456789" to construct candidate numbers of varying lengths and yields those that satisfy the range constraints. By using a generator, the implementation avoids materializing the entire result set in memory, delivering each valid number on demand.
Core Logic
The algorithm iterates over possible digit counts from 2 up to 9, because a sequential digit number cannot have more than nine digits without repeating or exceeding the digit '9'. For each digit count, it determines all feasible starting positions within the base string "123456789" that allow extraction of a substring of the required length. The substring is then converted to an integer and tested against the bounds low and high. When the integer lies inside the interval, it is emitted via yield.
for digits in range(2, 10):
for start in range(9 - digits + 1):
check = int("123456789"[start:digits+start])
if low <= check <= high:
yield check
Digit Count Loop
The outer loop enumerates the length of the sequential digit numbers. Starting at 2 ensures that single-digit numbers, which trivially satisfy the sequential property, are excluded because the problem definition typically expects at least two digits. The upper bound of 9 reflects the length of the source string, guaranteeing that the slice operation never exceeds its limits.
Starting Position Loop
The inner loop computes the range of valid starting indices for a given digit count. The expression 9 - digits + 1 calculates how many distinct substrings of the required length exist within "123456789". For example, when digits equals 3, the start index can be 0 through 6, yielding substrings "123", "234", …, "789".
Construction and Filtering
The slice "123456789"[start:digits+start] extracts a contiguous block of increasing digits. Converting this slice to an integer produces the candidate number check. The conditional low <= check <= high filters out numbers that fall outside the user-specified interval. Only numbers that satisfy the condition are emitted.
Edge Cases Handled
The code gracefully manages several boundary conditions:
- When
lowexceeds the largest possible sequential digit number (which is987654321for nine digits), the inner condition never becomes true, resulting in an empty generator without error. - When
highis smaller than the smallest two-digit sequential number (12), the same condition prevents any yields, again producing an empty sequence. - The loops automatically adapt to the situation where
lowandhighspan only a subset of possible digit lengths. For instance, if the range includes only three-digit numbers, the outer loop still iterates over all lengths, but the inner condition filters out numbers of other lengths. - The slice operation never raises an index error because the range of
startvalues is derived from the length of the source string and the current digit count, ensuring the slice stays within bounds for every iteration.
Performance Optimizations
The implementation incorporates several techniques that improve runtime efficiency and memory usage:
- String Reuse: The constant
"123456789"is defined once and reused for every slice operation, avoiding repeated construction of the base sequence. - Slice-Based Generation: By extracting substrings directly from the pre-ordered string, the algorithm sidesteps the need for arithmetic calculations to build each sequential number, which reduces computational overhead.
- Generator Pattern: Using
yieldturns the method into a lazy generator. This means that numbers are produced only when requested by the caller, eliminating the need to store the entire list of results in memory. The approach is especially beneficial when the caller consumes the output incrementally or stops early. - Early Filtering: The range check
low <= check <= highoccurs immediately after conversion, preventing unnecessary processing of numbers that are out of bounds. Since the loops continue even after the lower bound is passed, the condition still ensures that only relevant numbers are emitted.
Overall, the code delivers a concise solution that leverages the deterministic nature of sequential digits, minimizes redundant work, and provides results in a memory-efficient streaming fashion.
ELI5 - Simplified Explanation
Imagine a very special train that only drives in order. The cars on this train are numbered one, two, three, four, five, six, seven, eight, and nine. This Python code is like a game where the computer looks for all the different trains that can be made using these numbered cars in a row.
First, the code decides how long the train should be. It tries making a train with two cars, then three cars, and it keeps going until the train has nine cars.
Next, it looks at where the train starts. For each length, it slides along the row of numbers to pick a group of cars that stay in order. For example, it might pick one, দুই, and three to make a number train called one hundred twenty-three.
As it builds each number train, it checks two things. It looks at the lowest number provided and the highest number provided to see if the new train fits inside that range. If the train is not too small and not too big, it saves that train for later so the computer can show it to everyone. It keeps doing this until every possible train that fits in the range is found.
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 | Python | C++ | Java | TS | ||||
| WalkCCC | Python | C++ | Java | ||||||
| leetcode.ca | Python | C++ | Java | Go | TS | ||||
| Progiez | Python | C++ | Java | ||||||
| github | AdelDaniel | Dart | |||||||
| BigEggStudy | C# | ||||||||
| black-shadows | C++ | ||||||||
| chandansgowda | Python | ||||||||
| charles-wangkai | Java | ||||||||
| everthis | JS | ||||||||
| fpdjsns | C++ | ||||||||
| fsq | C++ | ||||||||
| Garvit244 | Python | ||||||||
| JoshCrozier | JS | ||||||||
| keineahnung2345 | C++ | ||||||||
| lkwq007 | Python | ||||||||
| muhammadfarhankt | Go | ||||||||
| pruthvikp | Python | ||||||||
| suxrobGM | C# | ||||||||
| trung-hn | Python | ||||||||
| varunu28 | Java | ||||||||
| withaarzoo | C++ | ||||||||
| YuriSpiridonov | Python | ||||||||
| AlgoMonster | C++, Python, Java, TypeScript | ||||||||
| WalkCCC | C++, Python, Java | ||||||||
| leetcode.ca | C++, Go, Java, Python, TypeScript | ||||||||
| Progiez | C++, Java, Python | ||||||||
| AdelDaniel | Dart | ||||||||
| BigEggStudy | C# | ||||||||
| black-shadows | C++, C++ | ||||||||
| chandansgowda | Python | ||||||||
| charles-wangkai | Java | ||||||||
| everthis | JavaScript | ||||||||
| fpdjsns | C++ | ||||||||
| fsq | C++ | ||||||||
| Garvit244 | Python | ||||||||
| JoshCrozier | JavaScript | ||||||||
| keineahnung2345 | C++ | ||||||||
| lkwq007 | Python | ||||||||
| muhammadfarhankt | Go | ||||||||
| pruthvikp | Python | ||||||||
| suxrobGM | C# | ||||||||
| trung-hn | Python | ||||||||
| varunu28 | Java | ||||||||
| withaarzoo | C++ | ||||||||
| YuriSpiridonov | Python |
Videos
Solved On The Same Day
- problem 845: Longest Mountain in Array
- problem 869: Reordered Power of 2
- problem 958: Check Completeness of a Binary Tree
- problem 988: Smallest String Starting From Leaf
- problem 753: Cracking the Safe
- problem 829: Consecutive Numbers Sum
- problem 1515: Best Position for a Service Centre
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