String with additive sequence | Set-2
Last Updated :
30 Mar, 2022
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 additive sequence.
Examples:
Input: str = “235813”
Output: true
Explanation : One of the possible sequence is: 2 , 3 , 5 , 8 , 13
where 3 = 1 + 2 , 5 = 3 + 2 , 8 = 5 + 3 and 13 = 8 + 5 .
Input: str = “199100199”
Output: true
Explanation : One of the possible sequence is : 1 , 99 , 100 , 199
where 100 = 99 + 1 , 199 = 100 + 99 gives the additive sequence.
Input: str = “12345678”
Output: false
Explanation: No such sequence possible
Approach: The recursive approach is discussed in Set-1 of this article.
Backtracking Approach: The above problem can be solved using Backtracking in the following way.
- One of the basic requirements according to the problem statement is to check whether the given string follows the property of additive sequence i.e. every number in the sequence is the sum of the previous two numbers and this property holds true for all the numbers in the sequence.
- So there is no restriction on how to choose the first two numbers in the sequence ( as exactly two numbers are needed to check the additive sequence property ).
- So try all the possible ways to generate the first two numbers in the series and from the third number onwards have a comparison i.e. in order to hold the additive sequence property the next number in the series must be the sum of the previous two numbers.
- So if at any point of time the number generated so far is exceeding the sum of the previous two numbers, there no longer is a need to proceed further because this number will never be a part of an additive sequence. In that case backtrack and try for the rest of the combinations.
- If the number generated so far is the sum of the previous two numbers then recur for the remaining string using the previous two numbers as a reference and if reach the end of the string and the length of the additive sequence ( size of the vector ) is greater than or equal to 3 then the given string had an additive sequence.
- The moment additive sequence is found mark a global boolean variable as true ( to indicate that we had found a solution and to avoid checking of rest of the combinations ).
Below is the implementation of the above.
C++
#include <bits/stdc++.h>
using namespace std;
bool res;
void check_additive(string s,
vector< long long >& v,
long st)
{
if (st == s.length() and v.size() > 2) {
res = true ;
return ;
}
long long a, b, c = 0;
if (v.size() >= 2) {
b = v[v.size() - 1];
a = v[v.size() - 2];
}
for ( long i = st; i < s.length(); i++) {
c = c * 10 + (s[i] - '0' );
if (v.size() < 2 and !res) {
v.push_back(c);
check_additive(s, v, i + 1);
v.pop_back();
}
else if (c > (a + b) and !res)
return ;
else if (c == a + b and !res) {
v.push_back(c);
check_additive(s, v, i + 1);
v.pop_back();
}
}
return ;
}
bool isAdditiveSequence(string str)
{
if (str.length() <= 2)
return false ;
vector< long long > v;
res = false ;
check_additive(str, v, 0);
return res;
}
int main()
{
string str = "199100199" ;
bool ans = isAdditiveSequence(str);
if (ans)
cout << "true" ;
else
cout << "false" ;
return 0;
}
|
Java
import java.util.ArrayList;
class GFG {
static boolean res;
static void check_additive(String s,
ArrayList<Integer> v,
int st)
{
if (st == s.length() && v.size() > 2 ) {
res = true ;
return ;
}
int a = 0 , b = 0 , c = 0 ;
if (v.size() >= 2 ) {
b = v.get(v.size() - 1 );
a = v.get(v.size() - 2 );
}
for ( int i = st; i < s.length(); i++) {
c = c * 10 + (s.charAt(i) - '0' );
if (v.size() < 2 && !res) {
v.add(c);
check_additive(s, v, i + 1 );
v.remove(v.size() - 1 );
}
else if (c > (a + b) && !res)
return ;
else if (c == a + b && !res) {
v.add(c);
check_additive(s, v, i + 1 );
v.remove(v.size() - 1 );
}
}
return ;
}
static boolean isAdditiveSequence(String str)
{
if (str.length() <= 2 )
return false ;
ArrayList<Integer> v = new ArrayList<Integer>();
res = false ;
check_additive(str, v, 0 );
return res;
}
public static void main(String args[]) {
String str = "199100199" ;
boolean ans = isAdditiveSequence(str);
if (ans)
System.out.println( "true" );
else
System.out.println( "false" );
}
}
|
Python3
res = 0
v = []
def check_additive(s, st):
global res
global v
if (st = = len (s) and len (v) > 2 ):
res = True
return
a, b, c = 0 , 0 , 0
if ( len (v) > = 2 ):
b = v[ len (v) - 1 ]
a = v[ len (v) - 2 ]
for i in range (st, len (s)):
c = c * 10 + ( ord (s[i]) - ord ( '0' ))
if ( len (v) < 2 and ( not res)):
v.append(c)
check_additive(s, i + 1 )
v.pop()
elif (c > (a + b) and not res):
return
elif (c = = a + b and not res):
v.append(c)
check_additive(s, i + 1 )
v.pop()
return
def isAdditiveSequence( str ):
global res
if ( len ( str ) < = 2 ):
return False
res = False
check_additive( str , 0 )
return res
if __name__ = = "__main__" :
str = "199100199"
ans = isAdditiveSequence( str )
if (ans):
print ( "true" )
else :
print ( "false" )
|
C#
using System;
using System.Collections.Generic;
class GFG
{
static bool res;
static void check_Additive( string s,
List< int > v,
int st)
{
if (st == s.Length && v.Count > 2) {
res = true ;
return ;
}
int a = 0, b = 0, c = 0;
if (v.Count >= 2) {
b = v[v.Count - 1];
a = v[v.Count - 2];
}
for ( int i = st; i < s.Length; i++) {
c = c * 10 + (s[i] - '0' );
if (v.Count < 2 && !res) {
v.Add(c);
check_Additive(s, v, i + 1);
v.Remove(v.Count - 1);
}
else if (c > (a + b) && !res)
return ;
else if (c == a + b && !res) {
v.Add(c);
check_Additive(s, v, i + 1);
v.Remove(v.Count - 1);
}
}
return ;
}
static bool isAdditiveSequence( string str)
{
if (str.Length <= 2)
return false ;
List< int > v = new List< int >();
res = true ;
check_Additive(str, v, 0);
return res;
}
public static void Main()
{
string str = "199100199" ;
bool ans = isAdditiveSequence(str);
if (ans)
Console.Write( "true" );
else
Console.Write( "false" );
}
}
|
Javascript
<script>
let res;
function check_additive(s,
v,
st) {
if (st == s.length && v.length > 2) {
res = true ;
return ;
}
let a, b, c = 0;
if (v.length >= 2) {
b = v[v.length - 1];
a = v[v.length - 2];
}
for (let i = st; i < s.length; i++) {
c = c * 10 + (s[i].charCodeAt(0) - '0' .charCodeAt(0));
if (v.length < 2 && res == false ) {
v.push(c);
check_additive(s, v, i + 1);
v.pop();
}
else if (c > (a + b) && res == false )
return ;
else if (c == a + b && res == false ) {
v.push(c);
check_additive(s, v, i + 1);
v.pop();
}
}
return ;
}
function isAdditiveSequence(str)
{
if (str.length <= 2)
return false ;
let v = [];
res = false ;
check_additive(str, v, 0);
return res;
}
let str = "199100199" ;
let ans = isAdditiveSequence(str);
if (ans)
document.write( "true" );
else
document.write( "false" );
</script>
|
Time Complexity: O(N*N)
Auxiliary Space: O(N)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...