Open In App

String with additive sequence

Improve
Improve
Like Article
Like
Save
Share
Report

Given a string, the task is to find whether it contains an additive sequence or not. A string contains an additive sequence if its digits can make a sequence of numbers in which every number is addition of previous two numbers. A valid string should contain at least three digit to make one additive sequence. 

Examples: 

Input : s = “235813”
Output : true
2 + 3 = 5, 3 + 5 = 8, 5 + 8 = 13

Input : s = “199100199”
Output : true
1 + 99 = 100, 99 + 100 = 199

Input : s = “12345678”
Output : false

Recommended Practice

This problem can be solved recursively, note that number of digits in added value can’t be smaller than digits in any of its operand that is why we will loop till (length of string)/2 for first number and (length of string – first number’s length)/ 2 for second number to ignore invalid result. 

Next thing to note is, first and second number can’t start with 0, which is checked in below code by isValid method. When we call recursively, we check that sum of first and second number is exactly equal to rest of string. If yes then direct return the result else check that sum string is prefix of rest of string or not, If yes then call recursively with second number, sum string and rest of string after removing sum string from rest of string and if sum string is not prefix of rest of string then no solution in available. 

Below is the implementation of the above approach:

CPP




// C++ program to check whether a string
// makes an additive sequence or not
#include <bits/stdc++.h>
using namespace std;
 
// Checks whether num is valid or not, by
// checking first character and size
bool isValid(string num)
{
    if (num.size() > 1 && num[0] == '0')
        return false;
    return true;
}
 
// returns int value at pos string, if pos is
// out of bound then returns 0
int val(string a, int pos)
{
    if (pos >= a.length())
        return 0;
 
    //  converting character to integer
    return (a[pos] - '0');
}
 
// add two number in string form and return
// result as a string
string addString(string a, string b)
{
    string sum = "";
    int i = a.length() - 1;
    int j = b.length() - 1;
    int carry = 0;
 
    //  loop until both string get processed
    while (i >= 0 || j >= 0) {
        int t = val(a, i) + val(b, j) + carry;
        sum += (t % 10 + '0');
        carry = t / 10;
        i--;
        j--;
    }
    if (carry)
        sum += (carry + '0');
    reverse(sum.begin(), sum.end());
    return sum;
}
 
//  Recursive method to check c = a + b
bool checkAddition(list<string>& res, string a, string b,
                   string c)
{
    //  both first and second number should be valid
    if (!isValid(a) || !isValid(b))
        return false;
    string sum = addString(a, b);
 
    //  if sum is same as c then direct return
    if (sum == c) {
        res.push_back(sum);
        return true;
    }
 
    /*  if sum size is greater than c, then no
        possible sequence further OR if c is not
        prefix of sum string, then no possible
        sequence further  */
    if (c.size() <= sum.size()
        || sum != c.substr(0, sum.size()))
        return false;
    else {
        res.push_back(sum);
 
        //  next recursive call will have b as first
        //  number, sum as second number and string
        //  c as third number after removing prefix
        //  sum string from c
        return checkAddition(res, b, sum,
                             c.substr(sum.size()));
    }
}
 
//  Method returns additive sequence from string as
// a list
list<string> additiveSequence(string num)
{
    list<string> res;
    int l = num.length();
 
    // loop until l/2 only, because if first
    // number is larger,then no possible sequence
    // later
    for (int i = 1; i <= l / 2; i++) {
        for (int j = 1; j <= (l - i) / 2; j++) {
            if (checkAddition(res, num.substr(0, i),
                              num.substr(i, j),
                              num.substr(i + j))) {
                // adding first and second number at
                // front of result list
                res.push_front(num.substr(i, j));
                res.push_front(num.substr(0, i));
                return res;
            }
        }
    }
 
    // If code execution reaches here, then string
    // doesn't have any additive sequence
    res.clear();
    return res;
}
 
//  Method to print result list
 
 
//  Driver code to test above methods
int main()
{
    string num = "235813";
    list<string> res = additiveSequence(num);
    if (res.size() > 0)
        cout << "True" << endl;
    else
        cout << "False" << endl;
 
    num = "199100199";
    res = additiveSequence(num);
    if (res.size() > 0)
        cout << "True" << endl;
    else
        cout << "False" << endl;
 
    return 0;
}


Java




// Java program for the above approach
import java.util.ArrayList;
import java.util.List;
 
public class AdditiveSequence {
 
    // Checks whether num is valid or not, by
    // checking first character and size
    private static boolean isValid(String num)
    {
        if (num.length() > 1 && num.charAt(0) == '0')
            return false;
        return true;
    }
 
    // returns int value at pos string, if pos is
    // out of bound then returns 0
    private static int val(String a, int pos)
    {
        if (pos >= a.length() || pos < 0)
            return 0;
 
        // converting character to integer
        return (a.charAt(pos) - '0');
    }
 
    // add two number in string form and return
    // result as a string
    private static String addString(String a, String b)
    {
        StringBuilder sum = new StringBuilder();
        int i = a.length() - 1;
        int j = b.length() - 1;
        int carry = 0;
 
        // loop until both string get processed
        while (i >= 0 || j >= 0) {
            int t = val(a, i) + val(b, j) + carry;
            sum.append(t % 10);
            carry = t / 10;
            i--;
            j--;
        }
        if (carry > 0)
            sum.append(carry);
        return sum.reverse().toString();
    }
 
    // Recursive method to check c = a + b
    private static boolean checkAddition(List<String> res,
                                         String a, String b,
                                         String c)
    {
        // both first and second number should be valid
        if (!isValid(a) || !isValid(b))
            return false;
        String sum = addString(a, b);
 
        // if sum is same as c then direct return
        if (sum.equals(c)) {
            res.add(sum);
            return true;
        }
 
        /* if sum size is greater than c, then no
                possible sequence further OR if c is not
                prefix of sum string, then no possible
                sequence further */
        if (c.length() <= sum.length()
            || !sum.equals(c.substring(0, sum.length())))
            return false;
        else {
            res.add(sum);
 
            // next recursive call will have b as first
            // number, sum as second number and string
            // c as third number after removing prefix
            // sum string from c
            return checkAddition(res, b, sum,
                                 c.substring(sum.length()));
        }
    }
 
    // Method returns additive sequence from string as
    // a list
    public static List<String> additiveSequence(String num)
    {
        List<String> res = new ArrayList<>();
        int l = num.length();
 
        // loop until l/2 only, because if first
        // number is larger,then no possible sequence
        // later
        for (int i = 1; i <= l / 2; i++) {
            for (int j = 1; j <= (l - i) / 2; j++) {
                if (checkAddition(res, num.substring(0, i),
                                  num.substring(i, i + j),
                                  num.substring(i + j))) {
                    // adding first and second number at
                    // front of result list
                    res.add(0, num.substring(0, i));
                    res.add(1, num.substring(i, i + j));
                    return res;
                }
            }
        }
 
        // If code execution reaches here, then string
        // doesn't have any additive sequence
        res.clear();
        return res;
    }
 
    // Method to print result list
 
    // Driver code to test above methods
    public static void main(String[] args)
    {
        String num = "235813";
        List<String> res = additiveSequence(num);
        if (res.size() > 0)
            System.out.println( "True");
        else
           System.out.println( "False");
        num = "199100199";
        res = additiveSequence(num);
        if (res.size() > 0)
            System.out.println( "True");
        else
          System.out.println( "True");
    }
}
 
// This code is contributed by Potta Lokesh


Python3




# Python program for the above approach
 
import collections
 
# Checks whether num is valid or not, by
# checking first character and size
 
 
def is_valid(num):
    if len(num) > 1 and num[0] == '0':
        return False
    return True
 
# returns int value at pos string, if pos is
# out of bound then returns 0
 
 
def val(a, pos):
    if pos < 0 or pos >= len(a):
        return 0
 
    #  converting character to integer
    return int(a[pos])
 
# add two number in string form and return
# result as a string
 
 
def add_string(a, b):
    sum_ = ""
    i = len(a) - 1
    j = len(b) - 1
    carry = 0
 
    #  loop until both string get processed
    while i >= 0 or j >= 0:
        t = val(a, i) + val(b, j) + carry
        sum_ += str(t % 10)
        carry = t // 10
        i -= 1
        j -= 1
    if carry:
        sum_ += str(carry)
    return sum_[::-1]
 
#  Recursive method to check c = a + b
 
 
def check_addition(res, a, b, c):
    #  both first and second number should be valid
    if not is_valid(a) or not is_valid(b):
        return False
    sum_ = add_string(a, b)
 
    #  if sum is same as c then direct return
    if sum_ == c:
        res.append(sum_)
        return True
 
    #  if sum size is greater than c, then no
    #  possible sequence further OR if c is not
    #  prefix of sum string, then no possible
    #  sequence further
    if len(c) <= len(sum_) or sum_ != c[:len(sum_)]:
        return False
    else:
        res.append(sum_)
        #  next recursive call will have b as first
        #  number, sum as second number and string
        #  c as third number after removing prefix
        #  sum string from c
        return check_addition(res, b, sum_, c[len(sum_):])
 
#  Method returns additive sequence from string as
# a list
 
 
def additive_sequence(num):
    res = collections.deque()
    l = len(num)
 
    # loop until l/2 only, because if first
    # number is larger, then no possible sequence
    # later
    for i in range(1, l//2 + 1):
        for j in range(1, (l-i)//2 + 1):
            if check_addition(res, num[:i], num[i:i+j], num[i+j:]):
                # adding first and second number at
                # front of result list
                res.appendleft(num[i:i+j])
                res.appendleft(num[:i])
                return res
 
    # If code execution reaches here, then string
    # doesn't have any additive sequence
    return res
 
 
#  Driver code to test above methods
if __name__ == "__main__":
    num = "235813"
    res = additive_sequence(num)
    if len(res) > 0:
      print("True");
    else:
      print("False");
 
    num = "199100199"
    res = additive_sequence(num)
    if len(res)>0:
      print("True");
    else:
      print("False");
 
# This code is contributed by adityashatmfh


C#




// C# program for the above approach
 
using System;
using System.Collections.Generic;
 
public class GFG {
 
    // Checks whether num is valid or not, by
    // checking first character and size
    private static bool IsValid(string num)
    {
        if (num.Length > 1 && num[0] == '0') {
            return false;
        }
        return true;
    }
 
    // returns int value at pos string, if pos is
    // out of bound then returns 0
    private static int Val(string a, int pos)
    {
        if (pos >= a.Length || pos < 0) {
            return 0;
        }
        // converting character to integer
        return (int)(a[pos] - '0');
    }
 
    // add two number in string form and return
    // result as a string
    private static string AddString(string a, string b)
    {
        char[] sum = new char[(Math.Max(a.Length, b.Length))];
        int i = a.Length - 1;
        int j = b.Length - 1;
        int carry = 0;
 
        // loop until both string get processed
        while (i >= 0 || j >= 0) {
            int t = Val(a, i) + Val(b, j) + carry;
            sum[(Math.Max(i, j))] = (char)(t % 10 + '0');
            carry = t / 10;
            i--;
            j--;
        }
        if (carry > 0) {
            return carry.ToString()
                + new string(sum).TrimEnd('\0');
        }
        return new string(sum).TrimEnd('\0');
    }
 
    // Recursive method to check c = a + b
    private static bool CheckAddition(List<string> res,
                                      string a, string b,
                                      string c)
    {
        // both first and second number should be valid
        if (!IsValid(a) || !IsValid(b)) {
            return false;
        }
        string sum = AddString(a, b);
 
        // if sum is same as c then direct return
        if (sum.Equals(c)) {
            res.Add(sum);
            return true;
        }
 
        /* if sum size is greater than c, then no
            possible sequence further OR if c is not
            prefix of sum string, then no possible
            sequence further */
        if (c.Length <= sum.Length
            || !sum.Equals(c.Substring(0, sum.Length))) {
            return false;
        }
        else {
            res.Add(sum);
 
            // next recursive call will have b as first
            // number, sum as second number and string
            // c as third number after removing prefix
            // sum string from c
            return CheckAddition(res, b, sum,
                                 c.Substring(sum.Length));
        }
    }
 
    // Method returns additive sequence from string as
    // a list
    public static List<string> AdditiveSequence(string num)
    {
        List<string> res = new List<string>();
        int l = num.Length;
 
        // loop until l/2 only, because if first
        // number is larger,then no possible sequence
        // later
        for (int i = 1; i <= l / 2; i++) {
            for (int j = 1; j <= (l - i) / 2; j++) {
                if (CheckAddition(res, num.Substring(0, i),
                                  num.Substring(i, j),
                                  num.Substring(i + j))) {
                    // adding first and second number at
                    // front of result list
                    res.Insert(0, num.Substring(0, i));
                    res.Insert(1, num.Substring(i, j));
                    return res;
                }
            }
        }
 
        // If code execution reaches here, then string
        // doesn't have any additive sequence
        res.Clear();
        return res;
    }
 
    // Driver code to test above methods
    public static void Main(string[] args)
    {
        string num = "235813";
        List<string> res = AdditiveSequence(num);
 
        if (res.Count > 0)
           Console.WriteLine("True ");
        else
           Console.WriteLine("False ");
        num = "199100199";
        res = AdditiveSequence(num);
         if (res.Count > 0)
           Console.WriteLine("True ");
        else
           Console.WriteLine("False ");
    }
}
 
// This code is contributed by Prince Kumar


Javascript




// Javascript program for the above approach
// Checks whether num is valid or not, by
// checking first character and size
function isValid(num) {
    if (num.length > 1 && num.charAt(0) === '0')
        return false;
    return true;
}
// returns int value at pos string, if pos is
// out of bound then returns 0
function val(a, pos) {
    if (pos >= a.length || pos < 0)
        return 0;
    // converting character to integer
    return parseInt(a.charAt(pos));
}
// add two number in string form and return
// result as a string
function addString(a, b) {
    let sum = "";
    let i = a.length - 1;
    let j = b.length - 1;
    let carry = 0;
    // loop until both string get processed
    while (i >= 0 || j >= 0) {
        let t = val(a, i) + val(b, j) + carry;
        sum = (t % 10) + sum;
        carry = Math.floor(t / 10);
        i--;
        j--;
    }
    if (carry > 0)
        sum = carry + sum;
    return sum;
}
 // Recursive method to check c = a + b
function checkAddition(res, a, b, c) {
    if (!isValid(a) || !isValid(b))
        return false;
    let sum = addString(a, b);
    if (sum === c) {
    res.push(sum);
    return true;
    }
    /* if sum size is greater than c, then no
    possible sequence further OR if c is not
    prefix of sum string, then no possible
    sequence further */
    if (c.length <= sum.length || sum !== c.substring(0, sum.length))
        return false;
    else {
        res.push(sum);
        // next recursive call will have b as first
        // number, sum as second number and string
        // c as third number after removing prefix
        // sum string from c
        return checkAddition(res, b, sum, c.substring(sum.length));
    }
}
 
function additiveSequence(num) {
    let res = [];
    let l = num.length;
     // loop until l/2 only, because if first
    // number is larger,then no possible sequence
    // later
    for (let i = 1; i <= l / 2; i++) {
        for (let j = 1; j <= (l - i) / 2; j++) {
            if (checkAddition(res, num.substring(0, i),
                num.substring(i, i + j), num.substring(i + j))) {
                     // adding first and second number at
                    // front of result list
                    res.unshift(num.substring(i, i + j));
                    res.unshift(num.substring(0, i));
                    return res;
            }
        }
    }
    // If code execution reaches here, then string
    // doesn't have any additive sequence
    res = [];
    return res;
}
 
 
let num = "235813";
let res = additiveSequence(num);
if(res.length >0)
console.log("True");
else
console.log("False");
 
let num2 = "199100199";
res = additiveSequence(num2);
if(res.length >0)
console.log("True");
else
console.log("False");


Output

True
True








The time complexity of this algorithm is O(n3) where n is the length of the string. This is because the outer two for loops iterate over the string for a maximum of n/2 and (n-i)/2 times respectively, and the checkAddition() function at each iteration of the two for loops takes O(n) time for each iteration.

The Auxiliary Space of this algorithm is O(n) because the recursive stack of the checkAddition() function is at most of size O(n).

Iterative Approach: 

The approach is the same as above, consider every possible starting point for the first and second number, then, get their substrings starting at that index, then, check whether they are the additive sum of those 2 strings. This approach takes constant space as, it do not require a recursive stack. 

C++




// C++ program to check whether a string
// makes an additive sequence or not
#include <bits/stdc++.h>
using namespace std;
 
 
//standard function to add two string
string strAdd(string s1, string s2){
    string sum;
    int c=0; //carry digit
     
    // traversing the two strings
    for(int i=s1.size()-1, j=s2.size()-1; i>=0 || j>=0; i--, j--){
         
        // add s1[i] - '0' to a
        int a=i>=0?(s1[i]-'0'):0;
        // add s2[j] - '0' to b
        int b=j>=0?(s2[j]-'0'):0;
        // sum them with carry, and take modulo with 10 to get value less than 9.
        // then add the old sum of it to ti
        sum=to_string((a+b+c)%10)+sum;
        // update the carray, it's 1 if greater than 10, else 0
        c=(a+b+c)/10;
    }
 
    // if carry found at last then add to the sum
    // for e.g. 999 + 1 = 1000
    return c?"1"+sum:sum;
}
 
// utility function which checks whether the current two strings
bool isAdditiveNumberUtil(string &num, string f, string s){
     
    int i = f.size() + s.size(); //starting pos for the next number after "s"
    while(i<num.size()){
         
        // if preceeding element is '0' in the string and string size is greater than 1,
        // then definitely we will not consider that case
        // for e.g.: "0123", f = "01", s = "23", then this will return false
        if((f.size()>1 && f[0]=='0') || (s.size()>1 && s[0]=='0')) break;
         
        // sum two strings
        string sum=strAdd(f, s);
         
        // if f + s == curr, where curr = substring starting at index i, with length num.size() - i
        if(sum==num.substr(i, num.size()-i)) return true; //valid till the end, found one solution, return true
         
        //continue validate:
        f=s;
        s=sum;
        i+=sum.size();
    }
    return false; //no find
}
 
 
//  Method returns additive sequence from string as
// a list
bool additiveSequence(string num) {
     
    // size of the string
    int n = num.size();
     
    // if size is less than 3, then never possible
    if(n < 3) return false;
     
    // considering every possible starting point of the first and second numbers
    for(int i = 0; i < n; i++)
        for(int j = i + 1; j < n; j++)
            // if found it's an additive number
            if(isAdditiveNumberUtil(num, num.substr(0, i+1), num.substr(i+1, j-i)))
                return true;
 
    // not found an additive number
    return false;
}
 
 
 
//  Driver code to test above methods
int main()
{
    string num = "235813";
    bool res = additiveSequence(num);
    if (res)
        cout << "True" << endl;
    else
        cout << "False" << endl;
 
    num = "199100199";
    res = additiveSequence(num);
    if (res)
        cout << "True" << endl;
    else
        cout << "False" << endl;
 
    return 0;
}


Java




// Java program to check whether a string
// makes an additive sequence or not
public class GFG {
    // Standard function to add two strings
    private static String strAdd(String s1, String s2)
    {
        StringBuilder sum = new StringBuilder();
        int carry = 0; // carry digit
 
        // Traversing the two strings
        for (int i = s1.length() - 1, j = s2.length() - 1;
             i >= 0 || j >= 0; i--, j--) {
 
            // Add s1[i] - '0' to a
            int a = i >= 0 ? (s1.charAt(i) - '0') : 0;
            // Add s2[j] - '0' to b
            int b = j >= 0 ? (s2.charAt(j) - '0') : 0;
            // Sum them with carry, and take modulo with 10
            // to get a value less than 9. Then add the old
            // sum of it to sum
            sum.insert(0, (a + b + carry) % 10);
            // Update the carry, it's 1 if greater than 10,
            // else 0
            carry = (a + b + carry) / 10;
        }
 
        // If carry found at last, then add it to the sum
        // For example, 999 + 1 = 1000
        return carry == 1 ? "1" + sum.toString()
                          : sum.toString();
    }
 
    // Utility function to check whether the current two
    // strings form an additive sequence
    private static boolean
    isAdditiveNumberUtil(String num, String f, String s)
    {
        int i = f.length()
                + s.length(); // Starting position for the
                              // next number after "s"
        while (i < num.length()) {
 
            // If preceding element is '0' in the string and
            // the string size is greater than 1, then it's
            // definitely not an additive number For
            // example: "0123", f = "01", s = "23", then
            // this will return false
            if ((f.length() > 1 && f.charAt(0) == '0')
                || (s.length() > 1 && s.charAt(0) == '0'))
                break;
 
            // Sum two strings
            String sum = strAdd(f, s);
 
            // If f + s == curr, where curr = substring
            // starting at index i, with length num.length()
            // - i
            if (sum.equals(num.substring(i))) {
                return true; // Valid till the end, found
                             // one solution, return true
            }
 
            // Continue validation
            f = s;
            s = sum;
            i += sum.length();
        }
        return false; // No valid additive sequence found
    }
 
    // Method to check if a string represents an additive
    // sequence
    private static boolean additiveSequence(String num)
    {
        int n = num.length();
 
        // If size is less than 3, then it's never possible
        if (n < 3)
            return false;
 
        // Considering every possible starting point of the
        // first and second numbers
        for (int i = 0; i < n; i++) {
            for (int j = i + 1; j < n; j++) {
                // If found, it's an additive number
                if (isAdditiveNumberUtil(
                        num, num.substring(0, i + 1),
                        num.substring(i + 1, j + 1))) {
                    return true;
                }
            }
        }
 
        // No valid additive sequence found
        return false;
    }
 
    // Driver code to test above methods
    public static void main(String[] args)
    {
        String num = "235813";
        boolean res = additiveSequence(num);
        if (res) {
            System.out.println("True");
        }
        else {
            System.out.println("False");
        }
 
        num = "199100199";
        res = additiveSequence(num);
        if (res) {
            System.out.println("True");
        }
        else {
            System.out.println("False");
        }
    }
}
 
// This code is contributed by shivamgupta310570


Python3




# Function to add two strings
def str_add(s1, s2):
    sum_str = ""
    carry = 0
 
    i = len(s1) - 1
    j = len(s2) - 1
    while i >= 0 or j >= 0:
        a = int(s1[i]) if i >= 0 else 0
        b = int(s2[j]) if j >= 0 else 0
 
        total = a + b + carry
        sum_str = str(total % 10) + sum_str
        carry = total // 10
 
        i -= 1
        j -= 1
 
    return "1" + sum_str if carry else sum_str
 
 
# Utility function to check whether the current two strings
# form an additive number or not
def is_additive_number_util(num, f, s):
    i = len(f) + len(s)
 
    while i < len(num):
        if (len(f) > 1 and f[0] == '0') or (len(s) > 1 and s[0] == '0'):
            break
 
        sum_str = str_add(f, s)
 
        if sum_str == num[i:]:
            return True
 
        f = s
        s = sum_str
        i += len(sum_str)
 
    return False
 
 
# Method to check if the given number forms an additive sequence
def is_additive_sequence(num):
    n = len(num)
 
    if n < 3:
        return False
 
    for i in range(n):
        for j in range(i + 1, n):
            if is_additive_number_util(num, num[:i + 1], num[i + 1: j + 1]):
                return True
 
    return False
 
 
# Driver code to test above methods
if __name__ == "__main__":
    num = "235813"
    res = is_additive_sequence(num)
    print("True" if res else "False")
 
    num = "199100199"
    res = is_additive_sequence(num)
    print("True" if res else "False")
 
# This code is contributed by rambabuguphka


C#




// C# program to check whether a string
// makes an additive sequence or not
using System;
 
class GFG {
    // standard function to add two string
    static string StrAdd(string s1, string s2)
    {
        string sum = string.Empty;
        int c = 0; // carry digit
 
        // traversing the two strings
        for (int i = s1.Length - 1, j = s2.Length - 1;
             i >= 0 || j >= 0; i--, j--) {
            // add s1[i] - '0' to a
            int a = i >= 0 ? (s1[i] - '0') : 0;
            // add s2[j] - '0' to b
            int b = j >= 0 ? (s2[j] - '0') : 0;
            // sum them with carry, and take modulo with 10
            // to get value less than 9. then add the old
            // sum of it to ti
            sum = ((a + b + c) % 10).ToString() + sum;
            // update the carry, it's 1 if greater than 10,
            // else 0
            c = (a + b + c) / 10;
        }
 
        // if carry found at last then add to the sum
        // for e.g. 999 + 1 = 1000
        return c != 0 ? "1" + sum : sum;
    }
 
    // utility function which checks whether the current two
    // strings
    static bool IsAdditiveNumberUtil(string num, string f,
                                     string s)
    {
        int i
            = f.Length + s.Length; // starting pos for the
                                   // next number after "s"
        while (i < num.Length) {
            // if preceding element is '0' in the string and
            // string size is greater than 1, then
            // definitely we will not consider that case for
            // e.g.: "0123", f = "01", s = "23", then this
            // will return false
            if ((f.Length > 1 && f[0] == '0')
                || (s.Length > 1 && s[0] == '0'))
                break;
 
            // sum two strings
            string sum = StrAdd(f, s);
 
            // if f + s == curr, where curr = substring
            // starting at index i, with length num.Length -
            // i
            if (sum == num.Substring(i, num.Length - i))
                return true; // valid till the end, found
                             // one solution, return true
 
            // continue validate:
            f = s;
            s = sum;
            i += sum.Length;
        }
        return false; // not found
    }
 
    // Method returns additive sequence from string as a
    // list
    static bool AdditiveSequence(string num)
    {
        // size of the string
        int n = num.Length;
 
        // if size is less than 3, then never possible
        if (n < 3)
            return false;
 
        // considering every possible starting point of the
        // first and second numbers
        for (int i = 0; i < n; i++) {
            for (int j = i + 1; j < n; j++) {
                // if found it's an additive number
                if (IsAdditiveNumberUtil(
                        num, num.Substring(0, i + 1),
                        num.Substring(i + 1, j - i)))
                    return true;
            }
        }
 
        // not found an additive number
        return false;
    }
 
    // Driver code to test above methods
    static void Main()
    {
        string num = "235813";
        bool res = AdditiveSequence(num);
        if (res)
            Console.WriteLine("True");
        else
            Console.WriteLine("False");
 
        num = "199100199";
        res = AdditiveSequence(num);
        if (res)
            Console.WriteLine("True");
        else
            Console.WriteLine("False");
    }
}
 
// This code is contributed by shivamgupta310570


Javascript




// Function to add two strings
function strAdd(s1, s2) {
    let sum = '';
    let c = 0; // carry digit
     
    for (let i = s1.length - 1, j = s2.length - 1; i >= 0 || j >= 0; i--, j--) {
        const a = i >= 0 ? parseInt(s1[i]) : 0;
        const b = j >= 0 ? parseInt(s2[j]) : 0;
         
        sum = `${(a + b + c) % 10}${sum}`;
        c = Math.floor((a + b + c) / 10);
    }
 
    return c ? `1${sum}` : sum;
}
 
// Utility function to check additive sequence
function isAdditiveNumberUtil(num, f, s) {
    let i = f.length + s.length;
     
    while (i < num.length) {
        if ((f.length > 1 && f[0] === '0') || (s.length > 1 && s[0] === '0')) break;
         
        const sum = strAdd(f, s);
         
        if (sum === num.substring(i, num.length)) return true;
         
        f = s;
        s = sum;
        i += sum.length;
    }
     
    return false;
}
 
// Function to check if a string follows additive sequence
function additiveSequence(num) {
    const n = num.length;
     
    if (n < 3) return false;
     
    for (let i = 0; i < n; i++) {
        for (let j = i + 1; j < n; j++) {
            if (isAdditiveNumberUtil(num,
                                     num.substring(0, i + 1),
                                     num.substring(i + 1, j + 1))) {
                return true;
            }
        }
    }
     
    return false;
}
 
// Test cases
let num = "235813";
let res = additiveSequence(num);
if (res)
    console.log("True");
else
    console.log("False");
 
num = "199100199";
res = additiveSequence(num);
if (res)
    console.log("True");
else
    console.log("False");


Output

True
True









Time Complexity: O(N^3) , where N is the size of the string 

Space Complexity: O(1) 



Last Updated : 19 Sep, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads