Python 0842.py
class Solution:
def splitIntoFibonacci(self, num: str) -> List[int]:
def deeper(a, b, have):
current = "".join([ str(h) for h in have ])
if len(current) > len(num):
return []
if len(current) == len(num):
return have if current == num else []
c = a + b
if c >= 2**31:
return [] # too big
# we could abort early if c mismatches but len(num) is quite small
return deeper(b, c, have + [ c ])
for i in range(1, len(num) - 2):
for j in range(i + 1, len(num) - 1):
a = int(num[:i])
b = int(num[i:j])
sequence = deeper(a, b, [ a, b ])
if len(sequence) >= 3: # empty if failed
return sequence
# no leading zero
if num[0] == "0" or num[i] == "0":
break
return []
Difficulty
and has an acceptance rate of about 41% (100k+ 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 provided implementation solves the problem of partitioning a numeric string into a Fibonacci-like sequence of integers. The algorithm explores possible first two numbers, then recursively builds the rest of the sequence while respecting the constraints of the Fibonacci rule, integer size limits, and string length matching. The design balances exhaustive search with early termination checks to keep the search space manageable.
Core Logic
The entry point is the splitIntoFibonacci method. It iterates over possible split positions for the first and second numbers using two nested loops. For each pair of candidate numbers it invokes a helper function that attempts to extend the sequence.
for i in range(1, len(num) - 2):
for j in range(i + 1, len(num) - 1):
a = int(num[:i])
b = int(num[i:j])
sequence = deeper(a, b, [a, b])
if len(sequence) >= 3:
return sequence
if num[0] == "0" or num[i] == "0":
break
The loops generate every feasible prefix for the first number (a) and every feasible suffix for the second number (b). The condition len(sequence) >= 3 ensures that only sequences with at least three elements are accepted as valid results.
Recursive Construction
The helper deeper receives the two most recent numbers of the current partial sequence (a and b) and the list of numbers built so far (have). It constructs the next expected Fibonacci number, checks constraints, and recurses.
def deeper(a, b, have):
current = "".join([str(h) for h in have])
if len(current) > len(num):
return []
if len(current) == len(num):
return have if current == num else []
c = a + b
if c >= 2**31:
return []
return deeper(b, c, have + [c])
The function first rebuilds the concatenated string representation of the sequence built so far. If this intermediate string already exceeds the length of the original input, the branch is abandoned. When the lengths match, a final equality check confirms that the constructed sequence exactly reproduces the input string. The next Fibonacci number c is computed as the sum of the two previous numbers. If c exceeds the 32-bit signed integer limit, the branch is terminated. Otherwise the recursion proceeds with the updated pair (b, c) and the extended list have + [c].
Loop Structure
The outer loops bound the search space by limiting the length of the first two numbers. The first loop runs from index 1 up to len(num) - 2, guaranteeing that at least one digit remains for the second number and the rest of the sequence. The inner loop starts one position after i and stops before the final character, ensuring that a third number can still be formed. This systematic enumeration guarantees that every viable pair of starting numbers is examined.
The early break condition inside the loops checks for leading zeros in the first or second number. If the character at the start of the string or at the split point i is '0', the loop terminates because any longer number would also begin with a zero, which is prohibited by the problem constraints.
Edge Cases
The implementation explicitly handles several edge conditions:
- Leading zeros: The check
if num[0] == "0" or num[i] == "0": breakprevents numbers with leading zeros from being considered, covering inputs such as"0123"or"1010"where a segment might start with zero. - Integer overflow: The guard
if c >= 2**31: return []stops recursion when the next Fibonacci term would exceed the 32-bit signed integer range, ensuring compliance with the required numeric limits. - Length mismatch: By comparing the length of the concatenated sequence string
currentwith the original input length, the code discards any partial sequence that cannot possibly match the full input, handling cases where the generated numbers would overshoot the string. - Exact match verification: When the lengths are equal, the equality test
return have if current == num else []confirms that the constructed sequence reproduces the original string exactly, handling scenarios where the numeric values line up but the string representation diverges due to leading zeros or extra digits.
Performance Considerations
The algorithm incorporates several optimizations that reduce unnecessary work:
- Early length pruning: The condition
if len(current) > len(num): return []aborts a recursive branch as soon as the built string becomes longer than the target, preventing deeper exploration of impossible paths. - Overflow cutoff: By checking the 32-bit limit before recursing, the code avoids generating and processing numbers that would be rejected later, saving both computation and memory.
- Leading zero early exit: The break statement inside the nested loops stops further exploration of longer prefixes once a leading zero is detected, eliminating a whole class of invalid candidates without additional recursion.
- String reconstruction only when needed: The concatenated representation
currentis built at the start of each recursive call, allowing the length checks to be performed before any further arithmetic, which is cheaper than generating the next number when the branch is already invalid. - Minimal state propagation: The recursive call passes only the two most recent numbers and the growing list, avoiding the need to recompute earlier parts of the sequence and keeping the recursion lightweight.
Through these measures the solution navigates the exponential search space efficiently enough for the typical input sizes encountered in the problem domain.
ELI5 - Simplified Explanation
Imagine you have a long string of numbers lined up in a row and you want to break them into smaller pieces to create a special game. This game is just like the Fibonacci sequence, where you pick two starting numbers, and every number that follows must be the sum of the two numbers right before it.
To solve this, the code acts like a curious explorer looking for these hidden patterns. First, it peeks at the front of the string to pick out two initial numbers. Once those two starting numbers are chosen, it starts a process to see if the rest of the string can be built by adding those numbers together over and over again.
The explorer keeps adding the last two numbers found to see if the result creates the next number in the line. If the new number matches the next part of the string, the explorer keeps going. If the numbers get too big to manage or stop matching the string, the explorer stops that path and tries different starting numbers instead.
There is a rule that none of the numbers are allowed to start with a zero unless the number itself is just zero. The search continues until the explorer finds a perfect sequence where every piece matches the original line of numbers without any left over. If the entire string is used up by these sums, the pieces are gathered together to show how the string was split apart.
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 | |||||||
| leetcode.ca | C++ | Java | Go | Python | |||||
| LeetcodeHelp | C++ | Java | Python | ||||||
| Progiez | C++ | Java | Python | ||||||
| github | black-shadows | C++ | |||||||
| charles-wangkai | Java | ||||||||
| halfrost | Go | ||||||||
| JoshCrozier | JS | ||||||||
| ruoru | Rust | ||||||||
| suxrobGM | C# | ||||||||
| zfang399 | C++ | ||||||||
| AlgoMonster | C++, Python, Java, TypeScript | ||||||||
| WalkCCC | C++, Java | ||||||||
| leetcode.ca | C++, Go, Java, Python | ||||||||
| LeetcodeHelp | C++, Java, Python | ||||||||
| Progiez | C++, Java, Python | ||||||||
| black-shadows | C++, C++ | ||||||||
| charles-wangkai | Java | ||||||||
| halfrost | Go | ||||||||
| JoshCrozier | JavaScript | ||||||||
| ruoru | Rust | ||||||||
| suxrobGM | C# | ||||||||
| zfang399 | C++ |
Videos
Similar Problems
- problem 306: Additive Number
- problem 509: Fibonacci Number
Solved On The Same Day
- problem 524: Longest Word in Dictionary through Deleting
- problem 529: Minesweeper
- problem 984: String Without AAA or BBB
- problem 1014: Best Sightseeing Pair
- problem 1017: Convert to Base -2
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