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:
Example 3:
π Constraints:
1 β€ s.length() β€ 100sconsists 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
len1from1ton-2, and forlen2from1ton - 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 + l2of 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++)
π§βπ» Code (Java)
π Code (Python)
π§ 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