Python 0306.py
class Solution:
def isAdditiveNumber(self, num: str) -> bool:
def deeper(a, b, s):
if not s:
return False
need = a + b
if need == int(s):
if need > 0 and s[0] != "0":
return True
if need == 0 and s == "0":
return True
for length in range(1, len(s)):
# no leading zeros
if s[0] == "0" and length > 1:
return False
have = int(s[:length])
if have == need:
return deeper(b, have, s[length:])
if have > need:
return False
return False
for i in range(1, len(num)):
for j in range(i+1, len(num)):
a = int(num[:i])
b = int(num[i:j])
# no leading zeros
if num[0] == "0" and i > 1:
break
if num[i] == "0" and j - i > 1:
break
if deeper(a, b, num[j:]):
return True
return False
Difficulty
and has an acceptance rate of about 34% (300k+ submissions).
Typical patterns to solve this problem:
- Backtracking
- String
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 Solution.isAdditiveNumber method determines whether a string of digits can be split into at least three numbers forming an additive sequence, where each number after the first two equals the sum of its two predecessors. The implementation explores possible partitions for the first two numbers and then recursively validates the remainder of the string.
Main Control Flow
The outermost part of the algorithm iterates over every feasible split point for the first number (a) and the second number (b). For each pair, it converts the corresponding substrings to integers and invokes the helper deeper to check the rest of the string.
for i in range(1, len(num)):
for j in range(i+1, len(num)):
a = int(num[:i])
b = int(num[i:j])
# no leading zeros
if num[0] == "0" and i > 1:
break
if num[i] == "0" and j - i > 1:
break
if deeper(a, b, num[j:]):
return True
The double loop guarantees that every combination of prefix lengths is examined, while the early break statements prune impossible choices caused by leading-zero violations.
Recursive Verification (deeper)
The nested function deeper(a, b, s) receives the two most recent numbers (a and b) and the remaining suffix s. Its purpose is to confirm whether s can be consumed by repeatedly matching the required sum need = a + b.
def deeper(a, b, s):
if not s:
return False
need = a + b
if need == int(s):
if need > 0 and s[0] != "0":
return True
if need == 0 and s == "0":
return True
If the entire suffix exactly equals the needed sum, the function returns True after confirming that the representation does not contain an illegal leading zero (except for the single digit zero). Otherwise, it attempts to consume a prefix of s that matches need.
for length in range(1, len(s)):
# no leading zeros
if s[0] == "0" and length > 1:
return False
have = int(s[:length])
if have == need:
return deeper(b, have, s[length:])
if have > need:
return False
return False
The loop iterates over possible prefix lengths, converting each candidate to an integer (have). When a candidate equals the required sum, recursion proceeds with the updated pair (b, have) and the remaining suffix. If a candidate exceeds the needed sum, the loop aborts because longer prefixes can only increase the numeric value, making a match impossible.
Edge Cases Handled
The code explicitly guards against numbers with leading zeros. In the outer loops, a prefix beginning with '0' is allowed only when its length is one; otherwise the loop terminates early:
if num[0] == "0" and i > 1:
break
if num[i] == "0" and j - i > 1:
break
Inside deeper, the same rule is applied to each examined segment of the suffix:
if s[0] == "0" and length > 1:
return False
Zero itself is treated as a valid number, but only when the substring is exactly "0". The condition
if need == 0 and s == "0":
return True
ensures that a sequence of zeros is accepted only when the representation matches the single-character zero, preventing spurious matches like "00".
Performance Optimizations
The algorithm incorporates several pruning techniques that reduce the search space:
-
Early termination on leading zeros - By breaking out of the outer loops as soon as a leading-zero violation is detected, the code avoids exploring longer prefixes that would inevitably be invalid.
-
Immediate failure when the candidate exceeds the required sum - Within
deeper, the momenthave > needthe loop returnsFalse. Since extending the prefix can only increasehave, further iterations cannot succeed, allowing the function to backtrack promptly. -
Direct success when the remaining suffix equals the needed sum - The check
if need == int(s):bypasses the inner loop entirely when the whole suffix matches the expected value, yielding an instant positive result without additional recursion. -
Minimal conversion overhead - Conversions from substring to integer are performed only when necessary: once for each candidate prefix and once for the final equality test. The code does not repeatedly recompute the same integer values.
These measures collectively keep the exploration tight, especially for inputs containing many zeros or large numeric values where mismatches become apparent early in the process.
ELI5 - Simplified Explanation
Imagine you have a long row of number blocks. This code acts like a detective trying to see if those blocks follow a special pattern. In this pattern, every new number is made by adding the two blocks that came right before it.
The code starts by picking the first two blocks to see what they are. Once it has those, it guesses what the next block should be by adding them together. If it finds a block that matches that guess, it moves forward and tries to find the next one by adding the previous two again.
It keeps zooming through the rest of the numbers, checking if the pattern stays true all the way to the end. The code is very careful about numbers starting with a zero because those usually do not follow the game rules. If it gets all the way through the row and every single block follows the addition rule, the game is a success. If it gets stuck or finds a block that does not belong, it goes back and tries picking different starting numbers to see if a different path works better.
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++ | Python | Java | |||||||
| leetcode.ca | C++ | Python | Java | Go | ||||||
| LeetcodeHelp | C++ | Python | Java | |||||||
| MemoryLimitExceeded | C++ | Python | ||||||||
| Progiez | C++ | Python | Java | |||||||
| github | aylei | Rust | ||||||||
| black-shadows | C++ | |||||||||
| charles-wangkai | Java | |||||||||
| everthis | JS | |||||||||
| halfrost | Go | |||||||||
| haoel | C++ | |||||||||
| JoshCrozier | JS | |||||||||
| linouk23 | C++ | |||||||||
| lkwq007 | Python | |||||||||
| ruoru | Rust | |||||||||
| suxrobGM | C# | |||||||||
| yuanliu666 | Kotlin | |||||||||
| zfang399 | C++ | |||||||||
| AlgoMonster | C++, Python, Java, TypeScript | |||||||||
| WalkCCC | C++, Python, Java | |||||||||
| leetcode.ca | C++, Go, Java, Python | |||||||||
| LeetcodeHelp | C++, Java, Python | |||||||||
| MemoryLimitExceeded | Python, C++ | |||||||||
| Progiez | C++, Java, Python | |||||||||
| aylei | Rust | |||||||||
| black-shadows | C++, C++ | |||||||||
| charles-wangkai | Java | |||||||||
| everthis | JavaScript | |||||||||
| halfrost | Go | |||||||||
| haoel | C++ | |||||||||
| JoshCrozier | JavaScript | |||||||||
| linouk23 | C++ | |||||||||
| lkwq007 | Python | |||||||||
| ruoru | Rust | |||||||||
| suxrobGM | C# | |||||||||
| yuanliu666 | Kotlin | |||||||||
| zfang399 | C++ |
Videos
Similar Problems
- problem 842: Split Array into Fibonacci Sequence
Solved On The Same Day
- problem 168: Excel Sheet Column Title
- problem 171: Excel Sheet Column Number
- problem 506: Relative Ranks
- problem 561: Array Partition
- problem 628: Maximum Product of Three Numbers
- problem 908: Smallest Range I
- problem 307: Range Sum Query - Mutable
- problem 378: Kth Smallest Element in a Sorted Matrix
- problem 692: Top K Frequent Words
- problem 720: Longest Word in Dictionary
- problem 910: Smallest Range II
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