Python 0967.py
class Solution:
def numsSameConsecDiff(self, n: int, k: int) -> List[int]:
result = []
def deeper(have):
if len(have) == n:
result.append(int(have))
return
previous = int(have[-1])
if previous + k <= 9:
deeper(have + str(previous + k))
if previous - k >= 0 and k > 0:
deeper(have + str(previous - k))
for i in range(1, 10): # no leading zero
deeper(str(i))
return result
Difficulty
and has an acceptance rate of about 59% (200k+ submissions).
Typical patterns to solve this problem:
- Backtracking
- Breadth First Search
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 class Solution with a method numsSameConsecDiff. The method generates all non-negative integers of length n where the absolute difference between every pair of consecutive digits is exactly k. The algorithm builds each candidate number digit by digit using depth-first recursion, collects the completed numbers, and returns them as a list.
Core Logic
The method starts by creating an empty list named result that will hold the final integers.
result = []
A nested helper function deeper is defined to perform the recursive construction. It receives a string have representing the digits chosen so far.
def deeper(have):
if len(have) == n:
result.append(int(have))
return
previous = int(have[-1])
if previous + k <= 9:
deeper(have + str(previous + k))
if previous - k >= 0 and k > 0:
deeper(have + str(previous - k))
The base case checks whether the current string length equals the target length n. When this condition is met, the string is converted to an integer and appended to result. The recursion then stops for that branch.
If the base case is not reached, the function extracts the last digit (previous) and attempts to extend the current number with a new digit that satisfies the required difference k. Two possibilities are explored:
- Adding
ktopreviouswhen the sum does not exceed 9. - Subtracting
kfrompreviouswhen the difference remains non-negative andkis positive (the second condition prevents duplicate work whenkis zero).
Each valid extension triggers a recursive call with the new digit appended to the string.
The outer loop initiates the recursion for every possible leading digit from 1 to 9, thereby avoiding numbers with a leading zero.
for i in range(1, 10): # no leading zero
deeper(str(i))
Finally, the method returns the populated result list.
return result
Edge Cases Handled
When k equals zero, the second conditional branch (previous - k >= 0 and k > 0) is deliberately disabled. This prevents the algorithm from exploring the same digit twice, which would otherwise generate duplicate entries for numbers like 111 or 222. The check ensures that only one recursive path is taken for each digit when the difference requirement collapses to equality.
The loop that starts recursion from 1 to 9 guarantees that numbers do not begin with a zero, satisfying the problem constraint that leading zeros are not allowed. Consequently, the algorithm correctly handles the case where n is 1 by still iterating over the range 1-9 and adding each single-digit number to the result.
If k is larger than 9, the conditions previous + k <= 9 and previous - k >= 0 will both fail for any digit, causing the recursion to terminate without adding any numbers. This behavior naturally yields an empty list, which aligns with the expectation that no valid numbers exist when the required difference cannot be satisfied.
Performance Optimizations
The recursion builds numbers as strings rather than as integer arithmetic during the construction phase. This avoids repeated integer conversion and multiplication by powers of ten, which can be more costly than simple string concatenation in Python. Only when a full length is reached does the code convert the string to an integer for storage.
The early termination checks (previous + k <= 9 and previous - k >= 0) prune branches that would lead to invalid digits. By preventing the creation of out-of-range numbers, the algorithm reduces the number of recursive calls dramatically, especially for larger values of k.
The condition k > 0 in the subtraction branch eliminates redundant exploration when k is zero. Without this guard, the algorithm would traverse two identical paths for each digit, effectively doubling the work. By skipping the second branch in that scenario, the implementation halves the recursion depth for the zero-difference case.
The outer loop restricts the starting digits to 1-9, which eliminates an entire class of invalid candidates that would begin with a zero. This pre-filtering reduces the initial recursion tree size and ensures that every generated number conforms to the leading-zero rule without additional checks later in the process.
ELI5 - Simplified Explanation
Imagine you have a long, empty train rack and you want to build some trains using special number blocks. Each block has a digit on it from zero to nine. You want to make a line of blocks that is exactly as long as the number n. There is one simple rule for the train: every time you add a new block, the new number must be a certain distance away from the one you just placed. That distance is called k.
First, you pick any starting block from one to nine to begin your train. You cannot start with a zero because that would look silly at the front of the train. Once you have your starting block, you look for the next block to add. You check if adding k to your current number keeps you at nine or below. If it does, you can snap that block onto the train. You also check if subtracting k keeps you at zero or above. If that works, you can snap that block on too.
This process continues like a game of follow the leader. Every time you find a new block that fits the rule, you add it to your train and keep looking for the next one. You keep building and adding blocks until your train reaches the right length. Whenever a train reaches the full length you wanted, you write that number down in a special notebook to keep track of all the different trains you managed to create. You restart the process for every starting number from one to nine until you have explored all the different ways to build your trains.
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++ | Python | Java | TS | ||||
| WalkCCC | C++ | Java | |||||||
| leetcode.ca | C++ | Python | Java | JS | Go | TS | |||
| LeetcodeHelp | C++ | Python | Java | ||||||
| Progiez | C++ | Python | Java | ||||||
| github | BigEggStudy | C# | |||||||
| black-shadows | C++ | ||||||||
| charles-wangkai | Java | ||||||||
| everthis | JS | ||||||||
| fartem | Ruby | ||||||||
| fsq | C++ | ||||||||
| JoshCrozier | JS | ||||||||
| keineahnung2345 | C++ | ||||||||
| lkwq007 | Python | ||||||||
| suxrobGM | C# | ||||||||
| trung-hn | Python | ||||||||
| varunu28 | Java | ||||||||
| vthwang | Java | ||||||||
| XiaotaoGuo | C++ | ||||||||
| YuriSpiridonov | Python | ||||||||
| AlgoMonster | C++, Python, Java, TypeScript | ||||||||
| WalkCCC | C++, Java | ||||||||
| leetcode.ca | C++, Go, Java, JavaScript, Python, TypeScript | ||||||||
| LeetcodeHelp | C++, Java, Python | ||||||||
| Progiez | C++, Java, Python | ||||||||
| BigEggStudy | C# | ||||||||
| black-shadows | C++, C++ | ||||||||
| charles-wangkai | Java | ||||||||
| everthis | JavaScript | ||||||||
| fartem | Ruby | ||||||||
| fsq | C++ | ||||||||
| JoshCrozier | JavaScript | ||||||||
| keineahnung2345 | C++ | ||||||||
| lkwq007 | Python | ||||||||
| suxrobGM | C# | ||||||||
| trung-hn | Python | ||||||||
| varunu28 | Java | ||||||||
| vthwang | Java | ||||||||
| XiaotaoGuo | C++ | ||||||||
| YuriSpiridonov | Python |
Videos
Solved On The Same Day
- problem 1175: Prime Arrangements
- problem 946: Validate Stack Sequences
- problem 2034: Stock Price Fluctuation
- problem 2375: Construct Smallest Number From DI String
- problem 2443: Sum of Number and Its Reverse
- problem 2521: Distinct Prime Factors of Product of Array
- problem 2601: Prime Subtraction Operation
- problem 2761: Prime Pairs With Target Sum
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