String with additive sequence
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
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 C++ implementation.
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 void printResult(list<string> res) { for ( auto it = res.begin(); it != res.end(); it++) cout << *it << " " ; cout << endl; } // Driver code to test above methods int main() { string num = "235813" ; list<string> res = additiveSequence(num); printResult(res); num = "199100199" ; res = additiveSequence(num); printResult(res); 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 private static void printResult(List<String> res) { for (String s : res) System.out.print(s + " " ); System.out.println(); } // Driver code to test above methods public static void main(String[] args) { String num = "235813" ; List<String> res = additiveSequence(num); printResult(res); num = "199100199" ; res = additiveSequence(num); printResult(res); } } // This code is contributed by Potta Lokesh |
2 3 5 8 13 1 99 100 199
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).
This article is contributed by Utkarsh Trivedi. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Login to comment...