Split a Numeric String into Fibonacci Sequence
Given a numeric string S representing a large number, the task is to form a Fibonacci Sequence of at least length 3 from the given string. If such a split is not possible, print -1.
Examples:
Input: S = “5712”
Output: 5 7 12
Explanation:
Since 5 + 7 = 12, the splits {5}, {7}, {12} forms a Fibonacci sequence.
Input: S = “11235813″
Output: 1 1 2 3 5 8 13
Approach:
To solve the problem, the idea is to use Backtracking to find a sequence that follows the conditions of the Fibonacci Sequence.
Follow the steps below to solve the problem:
- Initialize a vector seq[] to store the Fibonacci sequence.
- Initialize a variable pos which points to the current index of the string S, initially 0.
- Iterate over the indices [pos, length – 1]:
- Add the number S[pos: i] to the Fibonacci sequence seq if the length of seq is less than 2 or the current number is equal to the sum of the last two numbers of seq. Recur for the index i + 1 and proceed.
- If the last added number S[pos: i] does not form a Fibonacci sequence and returns false after recursion, then remove it from the seq.
- Otherwise, end the loop and return true as the Fibonacci sequence is formed.
- If pos exceeds the length of S, then:
- If the length of the sequence seq is greater than or equal to 3, then a Fibonacci sequence is found, hence return true.
- Otherwise, the Fibonacci sequence is not possible and hence returns false.
- Finally, if the length of seq is greater than or equal to 3, then print the numbers in seq as the required Fibonacci sequence or, otherwise print -1.
Below is the illustration of the recursive structure where only one branch is extended to get the result:
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
#define LL long long
bool splitIntoFibonacciHelper( int pos,
string S,
vector< int >& seq)
{
if (pos == S.length()
and (seq.size() >= 3)) {
return true ;
}
LL num = 0;
for ( int i = pos; i < S.length(); i++) {
num = num * 10 + (S[i] - '0' );
if (num > INT_MAX)
break ;
if (S[pos] == '0' and i > pos)
break ;
if (seq.size() > 2
and (num > ((LL)seq.back()
+ (LL)seq[seq.size()
- 2])))
break ;
if (seq.size() < 2
or (num == ((LL)seq.back()
+ (LL)seq[seq.size()
- 2]))) {
seq.push_back(num);
if (splitIntoFibonacciHelper(i + 1,
S, seq))
return true ;
seq.pop_back();
}
}
return false ;
}
void splitIntoFibonacci(string S)
{
vector< int > seq;
splitIntoFibonacciHelper(0, S,
seq);
if (seq.size() >= 3) {
for ( int i : seq)
cout << i << " " ;
}
else {
cout << -1;
}
}
int main()
{
string S = "11235813" ;
splitIntoFibonacci(S);
return 0;
}
|
Java
import java.util.*;
class GFG{
static boolean splitIntoFibonacciHelper( int pos,
String S,
ArrayList<Long> seq)
{
if (pos == S.length() && (seq.size() >= 3 ))
{
return true ;
}
long num = 0 ;
for ( int i = pos; i < S.length(); i++)
{
num = num * 10 + (S.charAt(i) - '0' );
if (num > Integer.MAX_VALUE)
break ;
if (S.charAt(pos) == '0' && i > pos)
break ;
if (seq.size() > 2 &&
(num > (( long )seq.get(seq.size() - 1 ) +
( long )seq.get(seq.size() - 2 ))))
break ;
if (seq.size() < 2 ||
(num == (( long )seq.get(seq.size() - 1 ) +
( long )seq.get(seq.size() - 2 ))))
{
seq.add(num);
if (splitIntoFibonacciHelper(i + 1 ,
S, seq))
return true ;
seq.remove(seq.size() - 1 );
}
}
return false ;
}
static void splitIntoFibonacci(String S)
{
ArrayList<Long> seq = new ArrayList<>();
splitIntoFibonacciHelper( 0 , S, seq);
if (seq.size() >= 3 )
{
for ( int i = 0 ; i < seq.size(); i++)
System.out.print(seq.get(i) + " " );
}
else
{
System.out.print( "-1" );
}
}
public static void main(String[] args)
{
String S = "11235813" ;
splitIntoFibonacci(S);
}
}
|
Python3
import sys
def splitIntoFibonacciHelper(pos, S, seq):
if (pos = = len (S) and ( len (seq) > = 3 )):
return True
num = 0
for i in range (pos, len (S)):
num = num * 10 + ( ord (S[i]) - ord ( '0' ))
if (num > sys.maxsize):
break
if ( ord (S[pos]) = = ord ( '0' ) and i > pos):
break
if ( len (seq) > 2 and
(num > (seq[ - 1 ] +
seq[ len (seq) - 2 ]))):
break
if ( len (seq) < 2 or
(num = = (seq[ - 1 ] +
seq[ len (seq) - 2 ]))):
seq.append(num)
if (splitIntoFibonacciHelper(
i + 1 , S, seq)):
return True
seq.pop()
return False
def splitIntoFibonacci(S):
seq = []
splitIntoFibonacciHelper( 0 , S, seq)
if ( len (seq) > = 3 ):
for i in seq:
print (i, end = ' ' )
else :
print ( - 1 , end = '')
if __name__ = = '__main__' :
S = "11235813"
splitIntoFibonacci(S)
|
C#
using System;
using System.Collections;
using System.Collections.Generic;
class GFG{
static bool splitIntoFibonacciHelper( int pos,
string S,
ArrayList seq)
{
if (pos == S.Length && (seq.Count >= 3))
{
return true ;
}
long num = 0;
for ( int i = pos; i < S.Length; i++)
{
num = num * 10 + (S[i] - '0' );
if (num > Int64.MaxValue)
break ;
if (S[pos] == '0' && i > pos)
break ;
if (seq.Count> 2 &&
(num > (( long )seq[seq.Count - 1] +
( long )seq[seq.Count - 2])))
break ;
if (seq.Count < 2 ||
(num == (( long )seq[seq.Count - 1] +
( long )seq[seq.Count - 2])))
{
seq.Add(num);
if (splitIntoFibonacciHelper(i + 1,
S, seq))
return true ;
seq.Remove(seq.Count - 1);
}
}
return false ;
}
static void splitIntoFibonacci( string S)
{
ArrayList seq = new ArrayList();
splitIntoFibonacciHelper(0, S, seq);
if (seq.Count >= 3)
{
for ( int i = 0; i < seq.Count; i++)
Console.Write(seq[i] + " " );
}
else
{
Console.Write( "-1" );
}
}
public static void Main( string [] args)
{
string S = "11235813" ;
splitIntoFibonacci(S);
}
}
|
Javascript
<script>
function splitIntoFibonacciHelper(pos, S, seq)
{
if (pos == S.length && (seq.length >= 3))
{
return true ;
}
let num = 0;
for (let i = pos; i < S.length; i++)
{
num = num * 10 + (S[i] - '0' );
if (num > Number.MAX_VALUE)
break ;
if (S[pos] == '0' && i > pos)
break ;
if (seq.length> 2 &&
(num > (seq[seq.length - 1] +
seq[seq.length - 2])))
break ;
if (seq.length < 2 ||
(num == (seq[seq.length - 1] +
seq[seq.length - 2])))
{
seq.push(num);
if (splitIntoFibonacciHelper(i + 1, S, seq))
return true ;
seq.pop();
}
}
return false ;
}
function splitIntoFibonacci(S)
{
let seq = [];
splitIntoFibonacciHelper(0, S, seq);
if (seq.length >= 3)
{
for (let i = 0; i < seq.length; i++)
document.write(seq[i] + " " );
}
else
{
document.write( "-1" );
}
}
let S = "11235813" ;
splitIntoFibonacci(S);
</script>
|
Time Complexity: O(N2)
Space Complexity: O(N)
Last Updated :
12 Oct, 2021
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...