306. Additive Number
Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.
Approach
The problem asks us to determine if a given string of digits can be partitioned into an additive sequence. An additive sequence must have at least three numbers. Starting from the third number, each number is the sum of the two preceding numbers. A key constraint is that numbers in the sequence cannot have leading zeros (e.g., 05 is invalid), though a single 0 is a valid number.
Solution
Additive Number in Python
class Solution:
def isAdditiveNumber(self, num: str) -> bool:
n = len(num)
# An additive sequence requires at least three numbers.
if n < 3:
return False
# i is the length of the first number.
for i in range(1, n // 2 + 1):
s1 = num[:i]
# The first number cannot have a leading zero unless it's just '0'.
if len(s1) > 1 and s1[0] == '0':
continue
# j is the length of the second number.
for j in range(1, n - i):
# Pruning: The remaining part must be at least as long as the longer of the first two numbers.
if max(i, j) > n - i - j:
break
s2 = num[i:i+j]
# The second number also cannot have a leading zero.
if len(s2) > 1 and s2[0] == '0':
continue
# If we find a valid pair, check if it forms an additive sequence.
if self.check(s1, s2, num, i + j):
return True
return False
def check(self, s1: str, s2: str, num: str, start: int) -> bool:
# Base case: successfully parsed the entire string.
if start == len(num):
return True
# Calculate sum and check if it's a prefix of the rest of the string.
s3 = self.add(s1, s2)
if not num.startswith(s3, start):
return False
# Recur for the next numbers in the sequence.
return self.check(s2, s3, num, start + len(s3))
def add(self, n1: str, n2: str) -> str:
# Helper for string addition. Python's built-in arbitrary-precision integers
# make this trivial (str(int(n1)+int(n2))), but this implementation is for demonstration
# and to answer the follow-up about handling large number overflows.
res = []
i, j = len(n1) - 1, len(n2) - 1
carry = 0
while i >= 0 or j >= 0 or carry:
d1 = int(n1[i]) if i >= 0 else 0
d2 = int(n2[j]) if j >= 0 else 0
sum_val = d1 + d2 + carry
res.append(str(sum_val % 10))
carry = sum_val // 10
i -= 1
j -= 1
return "".join(reversed(res))
Additive Number in Java
class Solution {
private String numStr;
private int n;
public boolean isAdditiveNumber(String num) {
this.numStr = num;
this.n = num.length();
if (n < 3) {
return false;
}
// i is the length of the first number
for (int i = 1; i <= n / 2; ++i) {
// j is the length of the second number
// Pruning: the rest must be at least as long as the max of the first two lengths
for (int j = 1; Math.max(i, j) <= n - i - j; ++j) {
// Check for leading zeros before creating substrings
if (numStr.charAt(0) == '0' && i > 1) {
continue;
}
if (numStr.charAt(i) == '0' && j > 1) {
continue;
}
String s1 = numStr.substring(0, i);
String s2 = numStr.substring(i, i + j);
if (check(s1, s2, i + j)) {
return true;
}
}
}
return false;
}
private boolean check(String s1, String s2, int start) {
// Base case: successfully parsed the whole string
if (start == n) {
return true;
}
String s3 = add(s1, s2);
// Check if the remaining string starts with the sum
if (!numStr.startsWith(s3, start)) {
return false;
}
// Recur for the next numbers in the sequence
return check(s2, s3, start + s3.length());
}
// Helper for string addition to handle large numbers
private String add(String n1, String n2) {
StringBuilder res = new StringBuilder();
int i = n1.length() - 1, j = n2.length() - 1, carry = 0;
while (i >= 0 || j >= 0 || carry > 0) {
int digit1 = i >= 0 ? n1.charAt(i--) - '0' : 0;
int digit2 = j >= 0 ? n2.charAt(j--) - '0' : 0;
int sum = digit1 + digit2 + carry;
res.append(sum % 10);
carry = sum / 10;
}
return res.reverse().toString();
}
}
Additive Number in C++
class Solution {
public:
bool isAdditiveNumber(string num) {
this->num_str = num;
this->n = num.length();
if (n < 3) {
return false;
}
// i is the length of the first number
for (int i = 1; i <= n / 2; ++i) {
// j is the length of the second number
// The rest of the string must be at least as long as the longer of the first two numbers.
for (int j = 1; max(i, j) <= n - i - j; ++j) {
string s1 = num.substr(0, i);
string s2 = num.substr(i, j);
// Check for leading zeros
if (s1.length() > 1 && s1[0] == '0') {
continue;
}
if (s2.length() > 1 && s2[0] == '0') {
continue;
}
// If a valid pair is found, check if it forms an additive sequence.
if (check(s1, s2, i + j)) {
return true;
}
}
}
return false;
}
private:
string num_str;
int n;
// Helper function for string addition to handle large numbers.
string add(string n1, string n2) {
string res = "";
int i = n1.length() - 1, j = n2.length() - 1, carry = 0;
while (i >= 0 || j >= 0 || carry) {
long long sum = carry + (i >= 0 ? n1[i--] - '0' : 0) + (j >= 0 ? n2[j--] - '0' : 0);
res.push_back(sum % 10 + '0');
carry = sum / 10;
}
reverse(res.begin(), res.end());
return res;
}
// Recursive helper to check if the rest of the string follows the additive sequence.
bool check(string s1, string s2, int start_index) {
// Base case: we have successfully parsed the entire string.
if (start_index == n) {
return true;
}
string s3 = add(s1, s2);
// Check if the rest of the string starts with the calculated sum.
if (start_index + s3.length() > n || num_str.compare(start_index, s3.length(), s3) != 0) {
return false;
}
// Recur for the next part of the sequence.
return check(s2, s3, start_index + s3.length());
}
};
Additive Number in TypeScript
function isAdditiveNumber(num: string): boolean {
const n = num.length;
if (n < 3) {
return false;
}
// Helper for string addition to handle large numbers
const add = (n1: string, n2: string): string => {
let res: string[] = [];
let i = n1.length - 1, j = n2.length - 1, carry = 0;
while (i >= 0 || j >= 0 || carry > 0) {
const d1 = i >= 0 ? parseInt(n1[i--]) : 0;
const d2 = j >= 0 ? parseInt(n2[j--]) : 0;
const sum = d1 + d2 + carry;
res.push((sum % 10).toString());
carry = Math.floor(sum / 10);
}
return res.reverse().join('');
};
// Recursive helper to check the rest of the string
const check = (s1: string, s2: string, start: number): boolean => {
if (start === n) {
return true;
}
const s3 = add(s1, s2);
if (!num.startsWith(s3, start)) {
return false;
}
return check(s2, s3, start + s3.length);
};
// i is the length of the first number
for (let i = 1; i <= Math.floor(n / 2); i++) {
// j is the length of the second number
// Pruning: the rest must be at least as long as the max of the first two lengths
for (let j = 1; Math.max(i, j) <= n - i - j; j++) {
const s1 = num.substring(0, i);
if (s1.length > 1 && s1[0] === '0') {
continue;
}
const s2 = num.substring(i, i + j);
if (s2.length > 1 && s2[0] === '0') {
continue;
}
if (check(s1, s2, i + j)) {
return true;
}
}
}
return false;
}
More Medium LeetCode answers
Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.
LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.