08. Sum-String
β GFG solution to the Sum String problem: check if a numeric string follows a sum sequence using string addition and recursion. π
The problem can be found at the following link: π Question Link
π§© Problem Description
Given a digit string s
, determine whether it can be split into more than two non-empty parts such that:
The rightmost part equals the integer sum of the two parts immediately before it.
This sum-rule applies recursively to the preceding parts.
No part may have leading zeros unless it is exactly
"0"
.
π Examples
Example 1:
Input: s = "12243660"
Output: true
Explanation:
Split as ["12","24","36","60"]:
36 = 12 + 24
60 = 24 + 36
Example 2:
Input: s = "1111112223"
Output: true
Explanation:
Split as ["1","111","112","223"]:
112 = 1 + 111
223 = 111 + 112
Example 3:
Input: s = "123456"
Output: false
Explanation:
No valid recursive sum-split exists.
π Constraints:
1 β€ s.length() β€ 100
s
consists only of digits'0'β'9'
.
β
My Approach
π‘ Idea
Try every possible pair of lengths for the first two numbers (
a
,b
).Skip any part that has a leading zero (length >1 and starts with
'0'
).Recursively check that each subsequent substring equals the string-sum of the previous two:
Use a helper
addStrings(x,y)
to compute their sum as a string.Compare with the next substring in
s
.
If we reach the end exactly, return
true
; otherwise backtrack.
βοΈ Algorithm Steps:
Let
n = s.length()
.For
len1
from1
ton-2
, and forlen2
from1
ton - len1 - 1
:If
s[0..len1-1]
ors[len1..len1+len2-1]
invalid (leading zero), continue.Call
check(0, len1, len2)
. If it returnstrue
, answertrue
.
If no split works, return
false
.
Helper bool check(int idx, int l1, int l2)
:
Extract
x = s.substr(idx, l1)
,y = s.substr(idx+l1, l2)
.Compute
z = addStrings(x,y)
; letl3 = z.length()
.If substring at
idx + l1 + l2
of lengthl3
βz
, returnfalse
.If exactly reached end, return
true
.Else recurse with
(idx + l1, l2, l3)
.
π Time and Auxiliary Space Complexity
Expected Time Complexity: O(nΒ³)
Triple nested loops over
(len1, len2)
and recursive checks with string-addition/substr of O(n) each.
Expected Auxiliary Space Complexity: O(n)
Recursion depth and temporary strings up to length n.
π§βπ» Code (C++)
class Solution {
public:
string addStrings(string a, string b) {
if (a.size() < b.size()) swap(a, b);
int carry = 0, n = a.size(), m = b.size();
string res = "";
for (int i = 0; i < m; ++i) {
int s = (a[n - 1 - i] - '0') + (b[m - 1 - i] - '0') + carry;
res = char(s % 10 + '0') + res;
carry = s / 10;
}
for (int i = m; i < n; ++i) {
int s = (a[n - 1 - i] - '0') + carry;
res = char(s % 10 + '0') + res;
carry = s / 10;
}
if (carry) res = char(carry + '0') + res;
return res;
}
bool check(string &s, int i, int l1, int l2) {
string x = s.substr(i, l1), y = s.substr(i + l1, l2);
if ((x[0] == '0' && l1 > 1) || (y[0] == '0' && l2 > 1)) return false;
string sum = addStrings(x, y);
int l3 = sum.size();
if (i + l1 + l2 + l3 > s.size()) return false;
if (sum != s.substr(i + l1 + l2, l3)) return false;
if (i + l1 + l2 + l3 == s.size()) return true;
return check(s, i + l1, l2, l3);
}
bool isSumString(string &s) {
int n = s.size();
for (int l1 = 1; l1 < n; ++l1)
for (int l2 = 1; l1 + l2 < n; ++l2)
if (check(s, 0, l1, l2)) return true;
return false;
}
};
π§βπ» Code (Java)
class Solution {
public boolean isSumString(String s) {
int n = s.length();
for (int l1 = 1; l1 < n; l1++) {
for (int l2 = 1; l1 + l2 < n; l2++) {
if (check(s, 0, l1, l2)) return true;
}
}
return false;
}
boolean check(String s, int i, int l1, int l2) {
String x = s.substring(i, i + l1), y = s.substring(i + l1, i + l1 + l2);
if ((x.length() > 1 && x.charAt(0) == '0') || (y.length() > 1 && y.charAt(0) == '0')) return false;
String sum = add(x, y);
int l3 = sum.length();
if (i + l1 + l2 + l3 > s.length()) return false;
String z = s.substring(i + l1 + l2, i + l1 + l2 + l3);
if (!sum.equals(z)) return false;
if (i + l1 + l2 + l3 == s.length()) return true;
return check(s, i + l1, l2, l3);
}
String add(String a, String b) {
if (a.length() < b.length()) return add(b, a);
StringBuilder sb = new StringBuilder();
int carry = 0, n = a.length(), m = b.length();
for (int i = 0; i < m; i++) {
int s = (a.charAt(n - 1 - i) - '0') + (b.charAt(m - 1 - i) - '0') + carry;
sb.append(s % 10);
carry = s / 10;
}
for (int i = m; i < n; i++) {
int s = (a.charAt(n - 1 - i) - '0') + carry;
sb.append(s % 10);
carry = s / 10;
}
if (carry > 0) sb.append(carry);
return sb.reverse().toString();
}
}
π Code (Python)
class Solution:
def isSumString(self, s: str) -> bool:
def add(a, b):
return str(int(a) + int(b))
def check(i, l1, l2):
x, y = s[i:i + l1], s[i + l1:i + l1 + l2]
if (len(x) > 1 and x[0] == '0') or (len(y) > 1 and y[0] == '0'):
return False
z = add(x, y)
l3 = len(z)
if i + l1 + l2 + l3 > len(s): return False
if s[i + l1 + l2:i + l1 + l2 + l3] != z: return False
if i + l1 + l2 + l3 == len(s): return True
return check(i + l1, l2, l3)
n = len(s)
for l1 in range(1, n):
for l2 in range(1, n - l1):
if check(0, l1, l2): return True
return False
π§ Contribution and Support
For discussions, questions, or doubts related to this solution, feel free to connect on LinkedIn: π¬ Any Questions?. Letβs make this learning journey more collaborative!
β If you find this helpful, please give this repository a star! β
πVisitor Count
Last updated