Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Practice Backtracking
  • Interview Problems on Backtracking
  • MCQs on Backtracking
  • Tutorial on Backtracking
  • Backtracking vs Recursion
  • Backtracking vs Branch & Bound
  • Print Permutations
  • Subset Sum Problem
  • N-Queen Problem
  • Knight's Tour
  • Sudoku Solver
  • Rat in Maze
  • Hamiltonian Cycle
  • Graph Coloring
Open In App
Next Article:
String Subsequence and Substring in Python
Next article icon

String with additive sequence

Last Updated : 16 Apr, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report
Try it on GfG Practice
redirect icon

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
Additive sequence
Try It!

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) {       // the length of the string cannot be less than 1.      // It is obvious that it should be atleast 1.     // It can also be greater than 1. Like in 1 9 9 1 0 0 => 1 + 99 => 100     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) {     // since we are decrementing the pos, we must check if it is less than 0     if (pos < 0))         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) 


Next Article
String Subsequence and Substring in Python

U

Utkarsh Trivedi
Improve
Article Tags :
  • Strings
  • Backtracking
  • DSA
Practice Tags :
  • Backtracking
  • Strings

Similar Reads

  • String with additive sequence | Set-2
    Given a string str, 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 digits to make one addi
    14 min read
  • String, Subsequence & Substring
    What is a Substring? A substring is a contiguous part of a string, i.e., a string inside another string. In general, for an string of size n, there are n*(n+1)/2 non-empty substrings. For example, Consider the string "geeks", There are 15 non-empty substrings. The subarrays are: g, ge, gee, geek, ge
    6 min read
  • Sequences and Series
    A sequence is an ordered list of numbers following a specific rule. Each number in a sequence is called a "term." The order in which terms are arranged is crucial, as each term has a specific position, often denoted as an​, where n indicates the position in the sequence. For example: 2, 5, 8, 11, 14
    7 min read
  • Consecutive sequenced numbers in a string
    Given a string s that contains only numeric digits, we need to check whether that strings contains numbers in a consecutive sequential manner in increasing order. If the string contains a valid sequence of consecutive integers, print "Yes" followed by the starting number of the sequence. Otherwise,
    6 min read
  • String Subsequence and Substring in Python
    Subsequence and Substring both are parts of the given String with some differences between them. Both of them are made using the characters in the given String only. The difference between them is that the Substring is the contiguous part of the string and the Subsequence is the non-contiguous part
    5 min read
  • Sequence and Series in Python
    Sequences and series are fundamental concepts in mathematics. A Sequence is an ordered list of numbers following a specific pattern, while a series is the sum of the elements of a sequence. This tutorial will cover arithmetic sequences, geometric sequences, and how to work with them in Python. Arith
    5 min read
  • Add two bit strings
    Given two binary strings s1 and s2 consisting of only 0s and 1s. Find the resultant string after adding the two Binary Strings.Note: The input strings may contain leading zeros but the output string should not have any leading zeros. Examples: Input: s1 = "1101", s2 = "111"Output: 10100Explanation:
    2 min read
  • Alternatively Merge two Strings
    Given 2 strings, merge them in an alternate way, i.e. the final string's first character is the first character of the first string, the second character of the final string is the first character of the second string and so on. And if once you reach end of one string while if another string is stil
    4 min read
  • Ticket Encoding Sequence
    You are working at a ticketing company that generates unique ticket codes for various events. You have given a number N and your task is to print the Nth ticket code. The ticket codes are generated based on a specific encoding sequence. The encoding sequence follows the recursive formula as describe
    8 min read
  • Introduction to Sequences
    A sequence is a list of numbers arranged in a specific order, following a particular rule. Each number in the sequence is called a term. In mathematics, a sequence is an ordered list of numbers, where each number in the list is called a term. Sequences are defined by a specific rule that determines
    7 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences