04. Sum-string
The problem can be found at the following link: Question Link
My Approach
I checked all possible combinations of substrings to find a valid sum-string. I iterate through the string, considering all possible splits into three substrings (num1, num2, and currSum). I add num1 and num2 using a helper function (add), and then compare the result with currSum. If they match, I continue the process recursively. To solve this, the functions are as follows:
Addition Function (
add):Takes two strings representing numbers and performs addition digit by digit.
Handles carry during addition.
Returns the result as a string.
Solver Function (
solve):Takes a string
sand indicesi,j, andk.Extracts three substrings from
s(num1, num2, currSum).Adds
num1andnum2using theaddfunction.Compares the result with currSum.
Recursively calls itself with updated indices.
Returns true if the entire string is a valid sum string.
Main Function (
isSumString):Iterates through all possible pairs of indices
(j, k).Calls
solveto check if the string is a valid sum string.Returns true if any valid sum string is found.
Time and Auxiliary Space Complexity
Time Complexity:
O(N^3), where N is the length of the input string.The nested loops iterate over all possible pairs of indices
(j, k).In the worst case, the
solvefunction has a time complexity ofO(N)per call.
Auxiliary Space Complexity:
O(N), whereNis the length of the input string.The recursive calls and string manipulations contribute to space complexity.
Code (C++)
Contribution and Support
For discussions, questions, or doubts related to this solution, please visit our discussion section. We welcome your input and aim to foster a collaborative learning environment.
If you find this solution helpful, consider supporting us by giving a ⭐ star to the getlost01/gfg-potd repository.
Last updated
Was this helpful?