Problem 842

Abstract / Summary

Split a string of digits into a sequence that forms a Fibonacci sequence.

Note

The full problem description, including helpful examples, can be found on LeetCode.

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 []
30 lines | 998 bytes | submitted October 13, 2023 | GitHub   18% comment ratio | tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 41% (100k+ submissions).

Typical patterns to solve this problem:
  • Backtracking
  • String
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
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.
LeetCode profile | GitHub repo

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": break prevents 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 current with 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 current is 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.

written by openai gpt

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.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 5 | μ = 5.78 | σ = 1.83

Complexity Analysis

Time: polynomial
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
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
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++
23 links | 12 authors | 8 languages

Videos

4 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

2 similar problems

Solved On The Same Day

5 medium
6 solutions   October 13, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • 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