Split a Numeric String into Fibonacci Sequence
Last Updated :
12 Oct, 2021
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++
// C++ program of the above approach
#include <bits/stdc++.h>
using namespace std;
#define LL long long
// Function that returns true if
// Fibonacci sequence is found
bool splitIntoFibonacciHelper(int pos,
string S,
vector<int>& seq)
{
// Base condition:
// If pos is equal to length of S
// and seq length is greater than 3
if (pos == S.length()
and (seq.size() >= 3)) {
// Return true
return true;
}
// Stores current number
LL num = 0;
for (int i = pos; i < S.length(); i++) {
// Add current digit to num
num = num * 10 + (S[i] - '0');
// Avoid integer overflow
if (num > INT_MAX)
break;
// Avoid leading zeros
if (S[pos] == '0' and i > pos)
break;
// If current number is greater
// than last two number of seq
if (seq.size() > 2
and (num > ((LL)seq.back()
+ (LL)seq[seq.size()
- 2])))
break;
// If seq length is less
// 2 or current number is
// is equal to the last
// two of the seq
if (seq.size() < 2
or (num == ((LL)seq.back()
+ (LL)seq[seq.size()
- 2]))) {
// Add to the seq
seq.push_back(num);
// Recur for i+1
if (splitIntoFibonacciHelper(i + 1,
S, seq))
return true;
// Remove last added number
seq.pop_back();
}
}
// If no sequence is found
return false;
}
// Function that prints the Fibonacci
// sequence from the split of string S
void splitIntoFibonacci(string S)
{
// Initialize a vector to
// store the sequence
vector<int> seq;
// Call helper function
splitIntoFibonacciHelper(0, S,
seq);
// If sequence length is
// greater than 3
if (seq.size() >= 3) {
// Print the sequence
for (int i : seq)
cout << i << " ";
}
// If no sequence is found
else {
// Print -1
cout << -1;
}
}
// Driver Code
int main()
{
// Given String
string S = "11235813";
// Function Call
splitIntoFibonacci(S);
return 0;
}
Java
// Java program of the above approach
import java.util.*;
class GFG{
// Function that returns true if
// Fibonacci sequence is found
static boolean splitIntoFibonacciHelper(int pos,
String S,
ArrayList<Long> seq)
{
// Base condition:
// If pos is equal to length of S
// and seq length is greater than 3
if (pos == S.length() && (seq.size() >= 3))
{
// Return true
return true;
}
// Stores current number
long num = 0;
for(int i = pos; i < S.length(); i++)
{
// Add current digit to num
num = num * 10 + (S.charAt(i) - '0');
// Avoid integer overflow
if (num > Integer.MAX_VALUE)
break;
// Avoid leading zeros
if (S.charAt(pos) == '0' && i > pos)
break;
// If current number is greater
// than last two number of seq
if (seq.size() > 2 &&
(num > ((long)seq.get(seq.size() - 1) +
(long)seq.get(seq.size() - 2))))
break;
// If seq length is less
// 2 or current number is
// is equal to the last
// two of the seq
if (seq.size() < 2 ||
(num == ((long)seq.get(seq.size() - 1) +
(long)seq.get(seq.size() - 2))))
{
// Add to the seq
seq.add(num);
// Recur for i+1
if (splitIntoFibonacciHelper(i + 1,
S, seq))
return true;
// Remove last added number
seq.remove(seq.size() - 1);
}
}
// If no sequence is found
return false;
}
// Function that prints the Fibonacci
// sequence from the split of string S
static void splitIntoFibonacci(String S)
{
// Initialize a vector to
// store the sequence
ArrayList<Long> seq = new ArrayList<>();
// Call helper function
splitIntoFibonacciHelper(0, S, seq);
// If sequence length is
// greater than 3
if (seq.size() >= 3)
{
// Print the sequence
for (int i = 0; i < seq.size(); i++)
System.out.print(seq.get(i) + " ");
}
// If no sequence is found
else
{
// Print -1
System.out.print("-1");
}
}
// Driver code
public static void main(String[] args)
{
// Given String
String S = "11235813";
// Function Call
splitIntoFibonacci(S);
}
}
// This code is contributed by offbeat
Python3
# Python3 program of the above approach
import sys
# Function that returns true if
# Fibonacci sequence is found
def splitIntoFibonacciHelper(pos, S, seq):
# Base condition:
# If pos is equal to length of S
# and seq length is greater than 3
if (pos == len(S) and (len(seq) >= 3)):
# Return true
return True
# Stores current number
num = 0
for i in range(pos, len(S)):
# Add current digit to num
num = num * 10 + (ord(S[i]) - ord('0'))
# Avoid integer overflow
if (num > sys.maxsize):
break
# Avoid leading zeros
if (ord(S[pos]) == ord('0') and i > pos):
break
# If current number is greater
# than last two number of seq
if (len(seq) > 2 and
(num > (seq[-1] +
seq[len(seq) - 2]))):
break
# If seq length is less
# 2 or current number is
# is equal to the last
# two of the seq
if (len(seq) < 2 or
(num == (seq[-1] +
seq[len(seq) - 2]))):
# Add to the seq
seq.append(num)
# Recur for i+1
if (splitIntoFibonacciHelper(
i + 1, S, seq)):
return True
# Remove last added number
seq.pop()
# If no sequence is found
return False
# Function that prints the Fibonacci
# sequence from the split of string S
def splitIntoFibonacci(S):
# Initialize a vector to
# store the sequence
seq = []
# Call helper function
splitIntoFibonacciHelper(0, S, seq)
# If sequence length is
# greater than 3
if (len(seq) >= 3):
# Print the sequence
for i in seq:
print(i, end = ' ')
# If no sequence is found
else:
# Print -1
print(-1, end = '')
# Driver Code
if __name__=='__main__':
# Given String
S = "11235813"
# Function Call
splitIntoFibonacci(S)
# This code is contributed by pratham76
C#
// C# program of the above approach
using System;
using System.Collections;
using System.Collections.Generic;
class GFG{
// Function that returns true if
// Fibonacci sequence is found
static bool splitIntoFibonacciHelper(int pos,
string S,
ArrayList seq)
{
// Base condition:
// If pos is equal to length of S
// and seq length is greater than 3
if (pos == S.Length && (seq.Count >= 3))
{
// Return true
return true;
}
// Stores current number
long num = 0;
for(int i = pos; i < S.Length; i++)
{
// Add current digit to num
num = num * 10 + (S[i] - '0');
// Avoid integer overflow
if (num > Int64.MaxValue)
break;
// Avoid leading zeros
if (S[pos] == '0' && i > pos)
break;
// If current number is greater
// than last two number of seq
if (seq.Count> 2 &&
(num > ((long)seq[seq.Count - 1] +
(long)seq[seq.Count - 2])))
break;
// If seq length is less
// 2 or current number is
// is equal to the last
// two of the seq
if (seq.Count < 2 ||
(num == ((long)seq[seq.Count - 1] +
(long)seq[seq.Count - 2])))
{
// Add to the seq
seq.Add(num);
// Recur for i+1
if (splitIntoFibonacciHelper(i + 1,
S, seq))
return true;
// Remove last added number
seq.Remove(seq.Count - 1);
}
}
// If no sequence is found
return false;
}
// Function that prints the Fibonacci
// sequence from the split of string S
static void splitIntoFibonacci(string S)
{
// Initialize a vector to
// store the sequence
ArrayList seq = new ArrayList();
// Call helper function
splitIntoFibonacciHelper(0, S, seq);
// If sequence length is
// greater than 3
if (seq.Count >= 3)
{
// Print the sequence
for(int i = 0; i < seq.Count; i++)
Console.Write(seq[i] + " ");
}
// If no sequence is found
else
{
// Print -1
Console.Write("-1");
}
}
// Driver Code
public static void Main(string[] args)
{
// Given String
string S = "11235813";
// Function call
splitIntoFibonacci(S);
}
}
// This code is contributed by rutvik_56
JavaScript
<script>
// Javascript program of the above approach
// Function that returns true if
// Fibonacci sequence is found
function splitIntoFibonacciHelper(pos, S, seq)
{
// Base condition:
// If pos is equal to length of S
// and seq length is greater than 3
if (pos == S.length && (seq.length >= 3))
{
// Return true
return true;
}
// Stores current number
let num = 0;
for(let i = pos; i < S.length; i++)
{
// Add current digit to num
num = num * 10 + (S[i] - '0');
// Avoid integer overflow
if (num > Number.MAX_VALUE)
break;
// Avoid leading zeros
if (S[pos] == '0' && i > pos)
break;
// If current number is greater
// than last two number of seq
if (seq.length> 2 &&
(num > (seq[seq.length - 1] +
seq[seq.length - 2])))
break;
// If seq length is less
// 2 or current number is
// is equal to the last
// two of the seq
if (seq.length < 2 ||
(num == (seq[seq.length - 1] +
seq[seq.length - 2])))
{
// Add to the seq
seq.push(num);
// Recur for i+1
if (splitIntoFibonacciHelper(i + 1, S, seq))
return true;
// Remove last added number
seq.pop();
}
}
// If no sequence is found
return false;
}
// Function that prints the Fibonacci
// sequence from the split of string S
function splitIntoFibonacci(S)
{
// Initialize a vector to
// store the sequence
let seq = [];
// Call helper function
splitIntoFibonacciHelper(0, S, seq);
// If sequence length is
// greater than 3
if (seq.length >= 3)
{
// Print the sequence
for(let i = 0; i < seq.length; i++)
document.write(seq[i] + " ");
}
// If no sequence is found
else
{
// Print -1
document.write("-1");
}
}
// Given String
let S = "11235813";
// Function call
splitIntoFibonacci(S);
// This code is contributed by suresh07.
</script>
Time Complexity: O(N2)
Space Complexity: O(N)
Similar Reads
C++ Program For Fibonacci Numbers The Fibonacci series is the sequence where each number is the sum of the previous two numbers. The first two numbers of the Fibonacci series are 0 and 1, and they are used to generate the entire series.Examples:Input: 5Output: 5Explanation: As 5 is the 5th Fibonacci number of series 0, 1, 1, 2, 3, 5
5 min read
TCS Coding Practice Question | Fibonacci Series Given a number 'n', the task is to print the Fibonacci series using Command Line Arguments. The Fibonacci numbers are the numbers in the following integer sequence. 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, ........ In mathematical terms, the sequence Fn of Fibonacci numbers is defined by the re
4 min read
Generating large Fibonacci numbers using boost library In our previous post on fibonacci series, we have seen many approaches to generate fibonacci numbers. In this approach, we shall be generating fibonacci numbers with the help of boost library. The program simply uses the "boost/multiprecision/cpp_int.hpp" boost library in which big_int is defined. T
5 min read
Split a string in equal parts such that all parts are palindromes Given a string str, the task is to split the string into minimum parts such that each part is of same length and each part is a palindrome. Print the required number of parts. Examples: Input: str = "civicbob" Output: 8 "b", "b", "c", "c", "i", "i", "v" and "o" are the required partitions. "civic" a
10 min read
Count of strings possible by replacing two consecutive same character with new character Given string str. The task is to count the number of all different strings possible if two consecutive same characters of the string can be replaced by one different character. Examples Input: str = "abclll" Output: 3 Explanation: There can be 3 different string including the original string as show
8 min read