Additive Number

Is the string a Fibonacci-like additive sequence? Backtrack over the first two summands.

Medium
Time O(n^3) Space O(n)
LeetCode
7 min read
backtracking string

Problem#

Return true iff num (digit string) is an additive sequence: at least 3 numbers, each (after the first two) equals the sum of the previous two. Leading zeros disallowed (except for "0" itself).

Examples#

  • "112358"true (1+1=2, 1+2=3, 2+3=5, 3+5=8)
  • "199100199"true

Approach#

Try every pair of starting summand lengths (len1, len2). Validate they don’t have leading zeros, then greedily extend by computing the next number = a + b until either matching the next substring or failing.

Solution#

Additive Number
class Solution {
public:
bool isAdditiveNumber(string num) {
int n = num.size();
auto noLeadingZero = [&](int start, int len) {
return len == 1 || num[start] != '0';
};
auto add = [](const string& a, const string& b) {
string s; int carry = 0, i = a.size() - 1, j = b.size() - 1;
while (i >= 0 || j >= 0 || carry) {
int x = (i >= 0 ? a[i--] - '0' : 0) + (j >= 0 ? b[j--] - '0' : 0) + carry;
s += '0' + x % 10;
carry = x / 10;
}
reverse(s.begin(), s.end());
return s;
};
for (int l1 = 1; l1 <= n / 2; ++l1) {
if (!noLeadingZero(0, l1)) break;
for (int l2 = 1; max(l1, l2) <= n - l1 - l2; ++l2) {
if (!noLeadingZero(l1, l2)) break;
string a = num.substr(0, l1), b = num.substr(l1, l2);
int pos = l1 + l2;
bool ok = true;
while (pos < n) {
string c = add(a, b);
if (pos + (int)c.size() > n || num.substr(pos, c.size()) != c) { ok = false; break; }
pos += c.size();
a = b; b = c;
}
if (ok && pos == n) return true;
}
}
return false;
}
};

Editorial#

Strings (not ints) for the running numbers handle arbitrary precision. Two nested loops choose the prefix lengths; the inner greedy verifies. The leading-zero rule trims the search early.

Complexity#

  • Time: O(n³).
  • Space: O(n).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.