Open In App

Check if a given string is sum-string

Last Updated : 22 Aug, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Given a string of digits, determine whether it is a ‘sum-string’. A string S is called a sum-string if the rightmost substring can be written as the sum of two substrings before it and the same is recursively true for substrings before it. 

Examples:

“12243660” is a sum string. 
Explanation : 24 + 36 = 60, 12 + 24 = 36

“1111112223” is a sum string. 
Explanation: 111+112 = 223, 1+111 = 112 

“2368” is not a sum string

In general, a string S is called sum-string if it satisfies the following properties:

sub-string(i, x) + sub-string(x+1, j) 
 = sub-string(j+1, l)
and 
sub-string(x+1, j)+sub-string(j+1, l) 
 = sub-string(l+1, m) 
and so on till end. 
Recommended Practice

From the examples, we can see that our decision depends on the first two chosen numbers. So we choose all possible first two numbers for a given string. Then for every chosen two numbers, we check whether it is sum-string or not? So the approach is very simple. We generate all possible first two numbers using two substrings s1 and s2 using two loops. then we check whether it is possible to make the number s3 = (s1 + s2) or not. If we can make s3 then we recursively check for s2 + s3 and so on. 

Implementation:

C++




// C++ program to check if a given string
// is sum-string or not
#include <bits/stdc++.h>
using namespace std;
 
// this is function for finding sum of two
// numbers as string
string string_sum(string str1, string str2)
{
    if (str1.size() < str2.size())
        swap(str1, str2);
 
    int m = str1.size();
    int n = str2.size();
    string ans = "";
 
    // sum the str2 with str1
    int carry = 0;
    for (int i = 0; i < n; i++) {
 
        // Sum of current digits
        int ds = ((str1[m - 1 - i] - '0')
                  + (str2[n - 1 - i] - '0') + carry)
                 % 10;
 
        carry = ((str1[m - 1 - i] - '0')
                 + (str2[n - 1 - i] - '0') + carry)
                / 10;
 
        ans = char(ds + '0') + ans;
    }
 
    for (int i = n; i < m; i++) {
        int ds = (str1[m - 1 - i] - '0' + carry) % 10;
        carry = (str1[m - 1 - i] - '0' + carry) / 10;
        ans = char(ds + '0') + ans;
    }
 
    if (carry)
        ans = char(carry + '0') + ans;
    return ans;
}
 
// Returns true if two substrings of given
// lengths of str[beg..] can cause a positive
// result.
bool checkSumStrUtil(string str, int beg, int len1,
                     int len2)
{
 
    // Finding two substrings of given lengths
    // and their sum
    string s1 = str.substr(beg, len1);
    string s2 = str.substr(beg + len1, len2);
    string s3 = string_sum(s1, s2);
 
    int s3_len = s3.size();
 
    // if number of digits s3 is greater than
    // the available string size
    if (s3_len > str.size() - len1 - len2 - beg)
        return false;
 
    // we got s3 as next number in main string
    if (s3 == str.substr(beg + len1 + len2, s3_len)) {
 
        // if we reach at the end of the string
        if (beg + len1 + len2 + s3_len == str.size())
            return true;
 
        // otherwise call recursively for n2, s3
        return checkSumStrUtil(str, beg + len1, len2,
                               s3_len);
    }
 
    // we do not get s3 in main string
    return false;
}
 
// Returns true if str is sum string, else false.
bool isSumStr(string str)
{
    int n = str.size();
 
    // choosing first two numbers and checking
    // whether it is sum-string or not.
    for (int i = 1; i < n; i++)
        for (int j = 1; i + j < n; j++)
            if (checkSumStrUtil(str, 0, i, j))
                return true;
 
    return false;
}
 
// Driver code
int main()
{
    bool result;
 
    result = isSumStr("1212243660");
    cout << (result == 1 ? "True\n" : "False\n");
       
    result = isSumStr("123456787");
    cout << (result == 1 ? "True\n" : "False\n");
    return 0;
}


Java




// Java program to check if a given string
// is sum-string or not
import java.util.*;
 
class GFG {
    // this is function for finding sum of two
    // numbers as string
    public static String string_sum(String str1,
                                    String str2)
    {
        if (str1.length() < str2.length()) {
            String temp = str1;
            str1 = str2;
            str2 = temp;
        }
        int m = str1.length();
        int n = str2.length();
        String ans = "";
 
        // sum the str2 with str1
        int carry = 0;
        for (int i = 0; i < n; i++) {
 
            // Sum of current digits
            int ds
                = ((str1.charAt(m - 1 - i) - '0')
                   + (str2.charAt(n - 1 - i) - '0') + carry)
                  % 10;
 
            carry
                = ((str1.charAt(m - 1 - i) - '0')
                   + (str2.charAt(n - 1 - i) - '0') + carry)
                  / 10;
 
            ans = Character.toString((char)(ds + '0'))
                  + ans;
        }
 
        for (int i = n; i < m; i++) {
            int ds = (str1.charAt(m - 1 - i) - '0' + carry)
                     % 10;
            carry = (str1.charAt(m - 1 - i) - '0' + carry)
                    / 10;
            ans = Character.toString((char)(ds + '0'))
                  + ans;
        }
 
        if (carry != 0) {
            ans = Character.toString((char)(carry + '0'))
                  + ans;
        }
        return ans;
    }
    // Returns true if two substrings of given
    // lengths of str[beg..] can cause a positive
    // result.
    public static boolean
    checkSumStrUtil(String str, int beg, int len1, int len2)
    {
 
        // Finding two substrings of given lengths
        // and their sum
        String s1 = str.substring(beg, beg + len1);
        String s2
            = str.substring(beg + len1, beg + len1 + len2);
        String s3 = string_sum(s1, s2);
 
        int s3_len = s3.length();
 
        // if number of digits s3 is greater than
        // the available string size
        if (s3_len > str.length() - len1 - len2 - beg)
            return false;
 
        // we got s3 as next number in main string
        if (s3.equals(str.substring(beg + len1 + len2,
                                    beg + len1 + len2
                                        + s3_len))) {
            // if we reach at the end of the string
            if (beg + len1 + len2 + s3_len
                == str.length()) {
                return true;
            }
 
            // otherwise call recursively for n2, s3
            return checkSumStrUtil(str, beg + len1, len2,
                                   s3_len);
        }
        // we do not get s3 in main string
        return false;
    }
    // Returns true if str is sum string, else false.
    public static boolean isSumStr(String str)
    {
        int n = str.length();
 
        // choosing first two numbers and checking
        // whether it is sum-string or not.
        for (int i = 1; i < n; i++)
            for (int j = 1; i + j < n; j++)
                if (checkSumStrUtil(str, 0, i, j))
                    return true;
 
        return false;
    }
    // Driver Code
    public static void main(String[] args)
    {
        boolean result;
        result = isSumStr("1212243660");
        System.out.println(result == true ? "True"
                                          : "False");
 
        result = isSumStr("123456787");
        System.out.println(result == true ? "True"
                                          : "False");
    }
}
 
// This code is contributed by Tapesh (tapeshdua420)


Python3




# Python code for the above approach
 
# this is function for finding sum of two
# numbers as string
def string_sum(str1, str2):
 
    if (len(str1) < len(str2)):
        str1, str2 = str2,str1
 
    m = len(str1)
    n = len(str2)
    ans = ""
 
    # sum the str2 with str1
    carry = 0
    for i in range(n):
 
        # Sum of current digits
        ds = ((ord(str1[m - 1 - i]) - ord('0')) +
                (ord(str2[n - 1 - i]) - ord('0')) +
                carry) % 10
 
        carry = ((ord(str1[m - 1 - i]) - ord('0')) +
                (ord(str2[n - 1 - i]) - ord('0')) +
                carry) // 10
 
        ans = str(ds) + ans
 
    for i in range(n,m):
        ds = (ord(str1[m - 1 - i]) - ord('0') +
                carry) % 10
        carry = (ord(str1[m - 1 - i]) - ord('0') +
                carry) // 10
        ans = str(ds) + ans
 
    if (carry):
        ans = str(carry) + ans
    return ans
 
# Returns True if two substrings of given
# lengths of str[beg..] can cause a positive
# result.
def checkSumStrUtil(Str, beg,len1, len2):
 
    # Finding two substrings of given lengths
    # and their sum
    s1 = Str[beg: beg+len1]
    s2 = Str[beg + len1: beg + len1 +len2]
    s3 = string_sum(s1, s2)
 
    s3_len = len(s3)
 
    # if number of digits s3 is greater than
    # the available string size
    if (s3_len > len(Str) - len1 - len2 - beg):
        return False
 
    # we got s3 as next number in main string
    if (s3 == Str[beg + len1 + len2: beg + len1 + len2 +s3_len]):
 
        # if we reach at the end of the string
        if (beg + len1 + len2 + s3_len == len(Str)):
            return True
 
        # otherwise call recursively for n2, s3
        return checkSumStrUtil(Str, beg + len1, len2,s3_len)
 
    # we do not get s3 in main string
    return False
 
# Returns True if str is sum string, else False.
def isSumStr(Str):
 
    n = len(Str)
 
    # choosing first two numbers and checking
    # whether it is sum-string or not.
    for i in range(1,n):
        for j in range(1,n-i):
            if (checkSumStrUtil(Str, 0, i, j)):
                return True
 
    return False
 
 
# Driver code
print(isSumStr("1212243660"))
print(isSumStr("123456787"))
 
# This code is contributed by shinjanpatra


C#




// C# program to check if a given string
// is sum-string or not
 
using System;
 
class sub_string {
    // this is function for finding sum of two
    // numbers as string
    static String string_sum(String str1, String str2)
    {
        if (str1.Length < str2.Length) {
            String temp = str1;
            str1 = str2;
            str2 = temp;
        }
 
        int m = str1.Length;
        int n = str2.Length;
        String ans = "";
 
        // sum the str2 with str1
        int carry = 0;
        for (int i = 0; i < n; i++) {
 
            // Sum of current digits
            int ds = ((str1[m - 1 - i] - '0')
                      + (str2[n - 1 - i] - '0') + carry)
                     % 10;
 
            carry = ((str1[m - 1 - i] - '0')
                     + (str2[n - 1 - i] - '0') + carry)
                    / 10;
 
            ans = (char)(ds + '0') + ans;
        }
 
        for (int i = n; i < m; i++) {
            int ds = (str1[m - 1 - i] - '0' + carry) % 10;
            carry = (str1[m - 1 - i] - '0' + carry) / 10;
            ans = (char)(ds + '0') + ans;
        }
 
        if (carry > 0)
            ans = (char)(carry + '0') + ans;
        return ans;
    }
 
    // Returns true if two substrings of given
    // lengths of str[beg..] can cause a positive
    // result.
    static bool checkSumStrUtil(String str, int beg,
                                int len1, int len2)
    {
 
        // Finding two substrings of given lengths
        // and their sum
        String s1 = str.Substring(beg, len1);
        String s2 = str.Substring(beg + len1, len2);
        String s3 = string_sum(s1, s2);
 
        int s3_len = s3.Length;
 
        // if number of digits s3 is greater than
        // the available string size
        if (s3_len > str.Length - len1 - len2 - beg)
            return false;
 
        // we got s3 as next number in main string
        if (s3
            == str.Substring(beg + len1 + len2, s3_len)) {
 
            // if we reach at the end of the string
            if (beg + len1 + len2 + s3_len == str.Length)
                return true;
 
            // otherwise call recursively for n2, s3
            return checkSumStrUtil(str, beg + len1, len2,
                                   s3_len);
        }
 
        // we do not get s3 in main string
        return false;
    }
 
    // Returns true if str is sum string, else false.
    static bool isSumStr(String str)
    {
        int n = str.Length;
 
        // choosing first two numbers and checking
        // whether it is sum-string or not.
        for (int i = 1; i < n; i++)
            for (int j = 1; i + j < n; j++)
                if (checkSumStrUtil(str, 0, i, j))
                    return true;
 
        return false;
    }
 
    // Driver code
    public static void Main()
    {
        Console.WriteLine(isSumStr("1212243660"));
        Console.WriteLine(isSumStr("123456787"));
    }
}
 
// This code is contributed by Abhijeet Kumar(abhijeet19403)


Javascript




<script>
 
// JavaScript code to implement the approach
 
// this is function for finding sum of two
// numbers as string
function string_sum(str1, str2){
 
    if (str1.length < str2.length){
        let temp = str1
        str1 = str2
        str2 = temp
 
    }
    let m = str1.length
    let n = str2.length
    let ans = ""
 
    // sum the str2 with str1
    let carry = 0
    for(let i=0;i<n;i++){
 
        // Sum of current digits
        let ds = ((str1.charCodeAt(m - 1 - i) - '0'.charCodeAt(0)) +
                (str2.charCodeAt(n - 1 - i) - '0'.charCodeAt(0)) +
                carry) % 10
 
        carry = Math.floor(((str1.charCodeAt(m - 1 - i) - '0'.charCodeAt(0)) +
                (str2.charCodeAt(n - 1 - i) - '0'.charCodeAt(0)) +
                carry) / 10)
 
        ans = ds.toString() + ans
    }
 
    for(let i=n;i<m;i++){
         
        let ds = ((str1.charCodeAt(m - 1 - i) - '0'.charCodeAt(0)) +
                (str2.charCodeAt(n - 1 - i) - '0'.charCodeAt(0)) +
                carry) % 10
 
        carry = Math.floor(((str1.charCodeAt(m - 1 - i) - '0'.charCodeAt(0)) +
                (str2.charCodeAt(n - 1 - i) - '0'.charCodeAt(0)) +
                carry) / 10)
 
        ans = ds.toString() + ans
    }
 
    if (carry)
        ans = carry.toString() + ans
    return ans
}
 
// Returns true if two substrings of given
// lengths of str[beg..] can cause a positive
// result.
function checkSumStrUtil(Str, beg,len1, len2){
    // Finding two substrings of given lengths
    // and their sum
    let s1 = Str.substring(beg,beg+len1)
    let s2 = Str.substring(beg + len1, beg + len1 +len2)
    let s3 = string_sum(s1, s2)
 
    let s3_len = s3.length
 
    // if number of digits s3 is greater than
    // the available string size
    if (s3_len > Str.length - len1 - len2 - beg)
        return false
 
    // we got s3 as next number in main string
    if (s3 == Str.substring(beg + len1 + len2, beg + len1 + len2 +s3_len)){
 
        // if we reach at the end of the string
        if (beg + len1 + len2 + s3_len == Str.length)
            return true
 
        // otherwise call recursively for n2, s3
        return checkSumStrUtil(Str, beg + len1, len2,s3_len)
    }
 
    // we do not get s3 in main string
    return false
}
 
// Returns true if str is sum string, else false.
function isSumStr(Str){
 
    let n = Str.length
 
    // choosing first two numbers and checking
    // whether it is sum-string or not.
    for(let i=1;i<n;i++){
        for(let j=1;j<n-i;j++){
            if (checkSumStrUtil(Str, 0, i, j))
                return true
        }
    }
 
    return false
}
 
 
// Driver code
document.write(isSumStr("1212243660"))
document.write(isSumStr("123456787"))
 
// This code is contributed by shinjanpatra
 
</script>


Output

True
False

Time Complexity: O(n*n*n), where n is the length of the string.
Auxiliary Space: O(n), where n is the length of the string.

 



Previous Article
Next Article

Similar Reads

Check if any permutation of a given string is lexicographically larger than the other given string
Given two strings str1 and str2 of same length N, the task is to check if there exists any permutation possible in any of the given strings, such that every character of one string is greater or equal to every character of the other string, at corresponding indices. Return true if permutation exists otherwise false. Example: Input: str1 = "adb", st
10 min read
Check if a given number can be expressed as pair-sum of sum of first X natural numbers
Given an integer N, the task is to check if N is the sum of a pair of integers which can be expressed as the sum of first X natural numbers, where X can be any positive integer. If satisfies the required condition. Print “YES”. Otherwise, print “NO”. Examples: Input: N = 25Output: YESExplanation:=&gt; 10 + 15 = 25Since 10 and 15 are the sum of firs
10 min read
Check if pair with given Sum exists in Array (Two Sum)
Given an array A[] of n numbers and another number x, the task is to check whether or not there exist two elements in A[] whose sum is exactly x. Examples: Input: arr[] = {0, -1, 2, -3, 1}, x= -2Output: YesExplanation: If we calculate the sum of the output,1 + (-3) = -2 Input: arr[] = {1, -2, 1, 0, 5}, x = 0Output: No Recommended PracticeKey PairTr
37 min read
Maximum sum subarray having sum less than given sum using Set
Given an array arr[] of length N and an integer K, the task is the find the maximum sum subarray with a sum less than K.Note: If K is less than the minimum element, then return INT_MIN. Examples: Input: arr[] = {-1, 2, 2}, K = 4 Output: 3 Explanation: The subarray with maximum sum which is less than 4 is {-1, 2, 2}. The subarray {2, 2} has maximum
7 min read
Maximum sum subarray having sum less than or equal to given sum
Given an array of non-negative integers and a sum. We have to find sum of the subarray having a maximum sum less than or equal to the given sum in the array. Note: Given array contains only non-negative integers. Examples: Input: arr[] = { 1, 2, 3, 4, 5 } sum = 11Output: 10Subarray having maximum sum is { 1, 2, 3, 4 }Input: arr[] = { 2, 4, 6, 8, 10
10 min read
Check if is possible to get given sum from a given set of elements
Given array of numbers and a integer x. Find whether it is possible or not to get x by adding elements of given array, we may pick a single element multiple times. For a given array, there can be many sum queries. Examples: Input : arr[] = { 2, 3} q[] = {8, 7} Output : Yes Yes Explanation : 2 + 2 + 2 + 2 = 8 2 + 2 + 3 = 7 The idea is to first sort
7 min read
Check if given integer is whole or partial sum of given Array elements
Given an integer K and an array A[] of size M, check if it is possible to obtain the integer K by taking the sum of one or more elements from the array A, with each element used at most once. Examples: Input: A[] = {1, 2, 3}, K = 6Output: TrueExplanation: 1 + 2 + 3 = 6 Input: A[] = {15, 12, 13, 10}, K = 20Output: False Approach: To solve the proble
6 min read
Check if the given array can be reduced to zeros with the given operation performed given number of times
Given an array arr[] of N integers and an integer K, the task is to find whether the given array elements can be made 0 if the given operation is applied exactly K times. In a single operation, the smallest element from the array will be subtracted from all the non-zero elements of the array.Examples: Input: arr[] = {1, 1, 2, 3}, K = 3 Output: Yes
6 min read
Check whether given string can be generated after concatenating given strings
Given three strings str, A and B. The task is to check whether str = A + B or str = B + A where + denotes concatenation. Examples: Input: str = "GeeksforGeeks", A = "Geeksfo", B = "rGeeks" Output: Yes str = A + B = "Geeksfo" + "rGeeks" = "GeeksforGeeks"Input: str = "Delhicapitals", B = "Delmi", C = "capitals" Output: No Approach: If len(str) != len
11 min read
Check if given Binary string follows then given condition or not
Given binary string str, the task is to check whether the given string follows the below condition or not: String starts with a '1'.Each '1' is followed by empty string(""), '1', or "00".Each "00" is followed by empty string(""), '1'. If the given string follows the above criteria then print "Valid String" else print "Invalid String".Examples: Inpu
10 min read