Problem 306

Abstract / Summary

Check if a string can be formed by adding numbers where each new number is the sum of the previous two.

Note

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

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
40 lines | 1198 bytes | submitted September 5, 2023 | GitHub   6% comment ratio | tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 34% (300k+ 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 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 moment have > need the loop returns False. Since extending the prefix can only increase have, 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.

written by openai gpt

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.

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 = 6 | μ = 5.89 | σ = 1.57

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++ 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++
32 links | 19 authors | 9 languages

Videos

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

Solved On The Same Day

6 easy 5 medium
12 solutions   September 5, 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