The goal is to split a given string S
into a Fibonacci-like sequence, where all the numbers follow the properties of the Fibonacci sequence. A sequence is Fibonacci-like if the sequence is split into F[0], F[1], ..., F[n]
such that:
F.length >= 3
F[i] + F[i+1] = F[i+2]
for all 0 <= i < F.length - 2
Return any such sequence of split numbers as a list of integers.
If it is not possible to split S
into a Fibonacci-like sequence, return an empty list.
S = "123456579"
Output: [123, 456, 579]
S = "11235813"
Output: [1, 1, 2, 3, 5, 8, 13]
S = "112358130"
[]
(It’s not possible to split such that all numbers follow the Fibonacci property.)1 <= len(S) <= 200
0
.S
is given to have at least one digit as per constraints.0
itself) is formed or if the numbers grow too large (greater than the maximum integer value).def splitIntoFibonacci(S: str):
def is_valid_number(number_str):
# To prevent large integer issues and leading zero issues
return len(number_str) == 1 or (number_str[0] != '0' and int(number_str) < 2**31)
def backtrack(index, path):
if index == len(S) and len(path) >= 3:
return path
current_number = 0
for i in range(index, len(S)):
current_number = current_number * 10 + int(S[i])
if not is_valid_number(S[index:i+1]):
break
if len(path) >= 2 and current_number != path[-1] + path[-2]:
if current_number > path[-1] + path[-2]:
break
continue
path.append(current_number)
result = backtrack(i + 1, path)
if result:
return result
path.pop()
return []
return backtrack(0, [])
# Example usage:
# print(splitIntoFibonacci("123456579")) # Outputs: [123, 456, 579]
The time complexity for this backtracking approach is difficult to precisely define due to the combination of substring generation and recursive tree exploration. However, in the worst case:
S
as the starting number which results in O(N^2) potential starting configurations.S
.A rough upper bound can be O(N^2 * 2^N)
, which should be acceptable given the input constraint 1 <= len(S) <= 200
.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?