Talentd
FleetCode
Make and follow sheets.Sign in

Additive Number solution and explanation

MediumBacktrackingString5 min read34.2% acceptanceUpdated 9 Apr 2026
Additive Number | LeetCode 306 | C++, PythonKnowledge Center · 34:02 · 13K viewsWatch on YouTube
9 more videos on this problem
  1. Additive Number | LeetCode 306 | C++, PythonKnowledge Center · 34:02 · 13K views
  2. LeetCode 306. Additive NumberHappy Coding · 27:09 · 3K views
  3. 306. Additive Number (Leetcode Medium)Programming Live with Larry · 14:24 · 3K views
  4. Additive Number | LeetCode 306 | Theory + Python codeSai Anish Malla · 19:12 · 2K views
  5. Leetcode Question 306 "Additive Number" in JavaGhumman Tech · 11:16 · 1K views
  6. Leetcode-306 additive number (Backtracking)You Wu · 22:34 · 1K views
  7. LeetCode 306. Additive Number | pythonEric Lee · 6:44 · 892 views
  8. Leetcode 306. Additive Number (backtracking)LetsCode · 18:19 · 410 views
  9. LeetCode 306. Additive Number | python | Chinese | 中文版Eric Lee · 7:44 · 311 views
  10. LeetCode 306 Additive Number (Java) (1-600三种语言完整视频讲解加微信flageek996网址flageek996.com)FLAGeek官方频道 · 2:44 · 86 views

The problem

An additive number is a string whose digits can form an additive sequence.

A valid additive sequence should contain at least three numbers. Except for the first two numbers, each subsequent number in the sequence must be the sum of the preceding two.

Given a string containing only digits, return true if it is an additive number or false otherwise.

Note: Numbers in the additive sequence cannot have leading zeros, so sequence 1, 2, 03 or 1, 02, 3 is invalid.

Example 1:

Input: "112358"
Output: true
Explanation: 
The digits can form an additive sequence: 1, 1, 2, 3, 5, 8. 
1 + 1 = 2, 1 + 2 = 3, 2 + 3 = 5, 3 + 5 = 8

Example 2:

Input: "199100199"
Output: true
Explanation: 
The additive sequence is: 1, 99, 100, 199. 
1 + 99 = 100, 99 + 100 = 199

Constraints:

  • 1 <= num.length <= 35
  • num consists only of digits.

Follow up: How would you handle overflow for very large input integers?

Approach overview

Problem Overview: You are given a numeric string num. The task is to determine whether it can form an additive sequence. In an additive sequence, every number (starting from the third) equals the sum of the previous two. Numbers cannot have leading zeros unless the number itself is 0.

Approach 1: Recursive Backtracking with Early Termination (O(n^3) time, O(n) space)

This approach tries all possible ways to split the first two numbers in the string, then recursively verifies whether the remaining string follows the additive rule. Start by choosing indices i and j to define the first two numbers. Convert them to integers (or use string-based addition to avoid overflow), compute their sum, and check if the next part of the string begins with that value. If it matches, continue the process recursively with the new pair. Early termination happens when a generated sum does not match the next substring, which prunes large parts of the search tree. The method naturally fits a backtracking pattern because you explore candidate splits and abandon invalid sequences quickly. Parsing and substring comparisons lead to O(n^3) time in the worst case, while recursion depth and substring storage require O(n) space.

Approach 2: Iterative Approach with Two Pointers (O(n^3) time, O(1) space)

This approach removes recursion and checks sequences iteratively. First, iterate over all possible splits for the first and second numbers using two pointers. After fixing these two values, simulate the additive sequence by repeatedly computing their sum and checking if the next substring matches it. If it matches, move the pointers forward and continue with the new pair. If any mismatch occurs, break early and try another split. Since you only track a few indices and temporary values, the extra space stays at O(1). However, generating candidate pairs and validating the remaining substring still leads to O(n^3) time complexity in the worst case. The approach mainly relies on careful string manipulation and controlled pointer movement similar to patterns used in two pointers problems.

Recommended for interviews: The recursive backtracking solution is usually preferred in interviews because it clearly expresses the search space and shows that you can prune invalid paths early. Interviewers expect you to handle leading zeros, large number addition, and substring validation carefully. The iterative version demonstrates strong control over pointer logic and space optimization. Showing the brute-force split idea first, then refining it with early termination, signals strong problem-solving skills.

Approach 1: Recursive Backtracking with Early Termination

This approach involves splitting the string into two initial numbers and trying to build valid subsequent numbers recursively. We backtrack if at any point the sequence condition is not met.

def is_additive_number(num):
    def is_valid(num1, num2, rest):
        if not rest:
            return True
        next_num = str(int(num1) + int(num2))
        if not rest.startswith(next_num):
            return False
        return is_valid(num2, next_num, rest[len(next_num):])

    n = len(num)
    for i in range(1, n//2 + 1):
        for j in range(1, n//2 + 1):
            num1, num2 = num[:i], num[i:i+j]
            if ((num1.startswith("0") and len(num1) > 1) or
                (num2.startswith("0") and len(num2) > 1)):
                continue
            if is_valid(num1, num2, num[i+j:]):
                return True
    return False
#include <stdbool.h>
#include <string.h>

bool is_valid(const char* num, int start, long long num1, long long num2) {
    if (start == strlen(num)) return true;

    long long sum = num1 + num2;
    char sum_str[50];
    sprintf(sum_str, "%lld", sum);
    int len = strlen(sum_str);

    if (strncmp(num + start, sum_str, len) != 0) return false;
    return is_valid(num, start + len, num2, sum);
}

bool isAdditiveNumber(char* num) {
    int n = strlen(num);
    for (int i = 1; i <= n / 2; ++i) {
        for (int j = 1; j <= (n - i) / 2; ++j) {
            if (num[0] == '0' && i > 1) break;
            if (num[i] == '0' && j > 1) break;

            long long num1 = atoll(strndup(num, i));
            long long num2 = atoll(strndup(num + i, j));

            if (is_valid(num, i + j, num1, num2)) return true;
        }
    }
    return false;
}

The solution defines a helper function is_valid that attempts to recursively verify the additive condition. We iterate over possible first and second numbers, ensuring no number has a leading zero unless it's single-digit. Backtracking is used when conditions fail at any step.

Complexity

Time Complexity: O(2^(N/2)), where N is the length of the string.
Space Complexity: O(N) due to recursion stack.

Try this approach in the editor

Approach 2: Iterative Approach with Two Pointers

This method uses two pointers to check possible partitions iteratively rather than recursively, aiming for reduced overhead and complexity by avoiding recursion.

public class Solution {
    public boolean isAdditiveNumber(String num) {
        int n = num.length();
        for (int i = 1; i <= n / 2; i++) {
            if (num.charAt(0) == '0' && i > 1) break;
            Long num1 = Long.parseLong(num.substring(0, i));
            for (int j = 1; Math.max(i, j) <= n - i - j; j++) {
                if (num.charAt(i) == '0' && j > 1) break;
                Long num2 = Long.parseLong(num.substring(i, i + j));
                if (isValid(i + j, num1, num2, num)) return true;
            }
        }
        return false;
    }

    private boolean isValid(int start, Long num1, Long num2, String num) {
        while (start < num.length()) {
            num2 = num2 + num1;
            num1 = num2 - num1;
            String sumStr = num2.toString();
            if (!num.substring(start).startsWith(sumStr)) return false;
            start += sumStr.length();
        }
        return true;
    }
}
function isAdditiveNumber(num) {
    const n = num.length;
    for (let i = 1; i <= Math.floor(n / 2); i++) {
        for (let j = 1; j <= Math.floor((n - i) / 2); j++) {
            if (num[0] == '0' && i > 1) break;
            if (num[i] == '0' && j > 1) break;

            const num1 = BigInt(num.substring(0, i));
            const num2 = BigInt(num.substring(i, i + j));

            if (isValid(i + j, num1, num2, num)) return true;
        }
    }
    return false;
}

function isValid(start, num1, num2, num) {
    while (start < num.length) {
        num2 = num2 + num1;
        num1 = num2 - num1;
        const sumStr = num2.toString();
        if (!num.substring(start).startsWith(sumStr)) return false;
        start += sumStr.length;
    }
    return true;
}

This Java solution leverages an iterative strategy with two pointers to avoid recursion. The method isValid checks the subsequent numbers by adjusting the indices accurately given two beginning numbers. Iteration continues only when the string matches the summation condition.

Complexity

Time Complexity: O(2^(N/2)) due to nested loops.
Space Complexity: O(1) since recursion is avoided.

Try this approach in the editor

Approach 3: Default Approach

class Solution {
public:
    bool isAdditiveNumber(string num) {
        int n = num.size();
        for (int i = 1; i < min(n - 1, 19); ++i) {
            for (int j = i + 1; j < min(n, i + 19); ++j) {
                if (i > 1 && num[0] == '0') break;
                if (j - i > 1 && num[i] == '0') continue;
                auto a = stoll(num.substr(0, i));
                auto b = stoll(num.substr(i, j - i));
                if (dfs(a, b, num.substr(j, n - j))) return true;
            }
        }
        return false;
    }

    bool dfs(long long a, long long b, string num) {
        if (num == "") return true;
        if (a + b > 0 && num[0] == '0') return false;
        for (int i = 1; i < min((int) num.size() + 1, 19); ++i)
            if (a + b == stoll(num.substr(0, i)))
                if (dfs(b, a + b, num.substr(i, num.size() - i)))
                    return true;
        return false;
    }
};
func isAdditiveNumber(num string) bool {
	n := len(num)
	var dfs func(a, b int64, num string) bool
	dfs = func(a, b int64, num string) bool {
		if num == "" {
			return true
		}
		if a+b > 0 && num[0] == '0' {
			return false
		}
		for i := 1; i < min(len(num)+1, 19); i++ {
			c, _ := strconv.ParseInt(num[:i], 10, 64)
			if a+b == c {
				if dfs(b, c, num[i:]) {
					return true
				}
			}
		}
		return false
	}
	for i := 1; i < min(n-1, 19); i++ {
		for j := i + 1; j < min(n, i+19); j++ {
			if i > 1 && num[0] == '0' {
				break
			}
			if j-i > 1 && num[i] == '0' {
				continue
			}
			a, _ := strconv.ParseInt(num[:i], 10, 64)
			b, _ := strconv.ParseInt(num[i:j], 10, 64)
			if dfs(a, b, num[j:]) {
				return true
			}
		}
	}
	return false
}
Try this approach in the editor

Complexity comparison

ApproachComplexity
Recursive Backtracking with Early Termination

Time Complexity: O(2^(N/2)), where N is the length of the string.
Space Complexity: O(N) due to recursion stack.

Iterative Approach with Two Pointers

Time Complexity: O(2^(N/2)) due to nested loops.
Space Complexity: O(1) since recursion is avoided.

Default Approach–

Complexity analysis

ApproachTimeSpaceWhen to Use
Recursive Backtracking with Early TerminationO(n^3)O(n)Best for interviews when demonstrating recursive exploration and pruning invalid sequences
Iterative Two-Pointer ValidationO(n^3)O(1)Useful when avoiding recursion or when memory usage must stay minimal

Frequently asked questions

Is Additive Number easy or hard?

Additive Number is considered a medium difficulty problem. The main challenge is correctly generating candidate splits, preventing numbers with leading zeros, and validating the sequence without overflow issues when numbers become large.

Additive Number Python/Java solution

Python solutions typically use recursion with substring slicing and integer or string-based addition. Java implementations often simulate the sequence iteratively using indices and string comparisons. Both follow the same idea: choose two starting numbers and verify whether the remaining digits match their additive sums.

How to solve Additive Number in O(n)?

An O(n) solution is not feasible because you must try multiple splits for the first two numbers before validating the rest of the sequence. The fastest practical approaches run in O(n^3) time due to O(n^2) starting choices and substring checks. Optimization mainly comes from early termination when a sequence fails.

What is the best approach for Additive Number?

Recursive backtracking with early termination is the most common approach. It tries all valid splits for the first two numbers and recursively checks whether the rest of the string follows the additive rule. Pruning invalid branches early keeps the search manageable. The overall time complexity is O(n^3) with O(n) recursion space.

Is Additive Number asked at Google/Amazon/Meta?

Additive Number is a classic string and backtracking problem that appears in technical interview practice sets and has been reported in interviews at companies like Amazon and Google. It tests string parsing, recursion, and careful handling of edge cases such as leading zeros and large numbers.

What data structure is used in Additive Number?

The problem mainly relies on string manipulation and arithmetic operations rather than complex data structures. Backtracking solutions use recursion to explore candidate sequences, while iterative approaches rely on pointer indices and substring comparisons.

What is the time complexity of Additive Number?

The typical solution runs in O(n^3) time. You try O(n^2) combinations for the first two numbers, and for each pair you may scan the rest of the string to validate the additive sequence. Space complexity ranges from O(1) in iterative solutions to O(n) with recursion.

Comments

Now write it yourselfClose this page and solve Additive Number in the editor, without looking.
Practise Additive Number