In this problem, You are given a string S of digits, such as S = "123456579", we can split it into a Fibonacci-like sequence [123, 456, 579]. Formally, a Fibonacci-like sequence is a list F of non-negative integers such that:
1: 0 <= F[i] <= 2^31 - 1, (that is, each integer fits a 32-bit signed integer type);
2: F.length >= 3;
3: and F[i] + F[i+1] = F[i+2] for all 0 <= i < F.length - 2.
Also, note that when splitting the string into pieces, each piece must not have extra leading zeroes, except if the piece is the number 0 itself.
Return any Fibonacci-like sequence split from S, or return [] if it cannot be done.
Example :Input: "123456579"
Output: [123, 456, 579]
Explanation:
Since 123 + 456 = 579, therefore the given string can be broken into fibonacci sequence
The first line of input contains a single integer βTβ denoting the number of test cases given.
The first line of each test case input contains a string that is required to be broken into different Fibonacci sequences.
Output Format:
For every test case, Return the first Fibonacci-like sequence list (array) which can be formed by splitting from S, or return [] if it cannot be done.
Note:
You do not need to print anything; it has already been taken care of. Just implement the given function.
Constraint :
1 <= T <= 100
1 <= S.length <= 200
Time Limit: 1 sec
3
1101111
112358130
0123
YES
NO
NO
For the first test case, The output [11, 0, 11, 11] is the required Fibonacci sequence here. So since there is one such sequence available, therefore, the output is βYESβ here.
For the second test case, The task of splitting the string into a Fibonacci sequence is not Possible. Therefore you output an empty list (array). The result here would be βNOβ.
For the third test case, Since there are Leading zeroes, which are not allowed, so "01", "2", "3" is not a valid Fibonacci sequence. Hence the result βNOβ.
2
123456579
11235813
YES
YES
Try to notice the fact that the first two elements of the array can be uniquely used to determine the rest of the sequence.
Using the above intuition, we can formalize the following concept that, the first two elements which our resultant Fibonacci sequence list (array) will contain, uniquely helps us determine and figure out the rest of the sequence.
For each of the first two elements, assuming they have no leading zero, let's iterate through the rest of the string. At each stage, we expect a number less than or equal to 2^31 - 1 that starts with the sum of the two previous numbers.
The algorithm to calculate the required smallest difference will be:-
O(N * N), where βNβ is the length of the βSβ.
Since we are iterating over all the elements given in the string βSβ which is an O(N) operation and doing so in a nested fashion to find the first two Fibonacci numbers in the sequence which could uniquely deter
O(N), where βNβ is the length of the βSβ.
Since, Here, we use a list (array) to store the required Fibonacci sequence, therefore, the space complexity is O(N).