You are given a string of digits num
, such as "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:
0 <= f[i] < 2^31
, (that is, each integer fits in a 32-bit signed integer type),f.length >= 3
, andf[i] + f[i + 1] == f[i + 2]
for all 0 <= i < f.length - 2
.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.
Write a function that will return any Fibonacci-like sequence split from num
, or return []
if it cannot be done.
Example 1:
Input: num = "1101111"
Output: [11,0,11,11]
Explanation: The output [110, 1, 111] would also be accepted.
Example 2:
Input: num = "112358130"
Output: []
Explanation: The task is impossible.
Example 3:
Input: num = "0123"
Output: []
Explanation: Leading zeroes are not allowed, so "01", "2", "3" is not valid.
What is the time and space complexity of your solution?
When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:
The brute force approach to splitting a sequence into a Fibonacci sequence involves trying every single way to divide the numbers. We explore all combinations to see if any of them form a valid Fibonacci sequence.
Here's how the algorithm would work step-by-step:
def split_into_fibonacci_brute_force(input_string):
length_of_input = len(input_string)
result = []
def backtrack(current_index, sequence):
if current_index == length_of_input and len(sequence) >= 3:
result.append(sequence)
return True
for j in range(current_index + 1, length_of_input + 1):
number_string = input_string[current_index:j]
# Prevent leading zeros
if number_string.startswith('0') and len(number_string) > 1:
continue
current_number = int(number_string)
# Check for integer overflow
if current_number > 2**31 - 1:
continue
if len(sequence) < 2:
if backtrack(j, sequence + [current_number]):
return True
else:
# Validate the fibonacci condition
if sequence[-1] + sequence[-2] == current_number:
if backtrack(j, sequence + [current_number]):
return True
return False
backtrack(0, [])
if result:
return result[0]
else:
return []
The challenge is to break a string of digits into a Fibonacci sequence. The best way to do this is to try building the sequence one number at a time, making sure each new number follows the Fibonacci rule (it equals the sum of the previous two). If it doesn't, we backtrack and try a different starting point or number length.
Here's how the algorithm would work step-by-step:
def split_into_fibonacci(digit_string):
sequence_list = []
string_length = len(digit_string)
def backtrack(index_position):
if index_position == string_length and len(sequence_list) >= 3:
return True
for j in range(index_position + 1, string_length + 1):
substring = digit_string[index_position:j]
# Leading zero check.
if len(substring) > 1 and substring[0] == '0':
continue
try:
number = int(substring)
except ValueError:
continue
# Number should be within 32 bit range.
if number >= (1 << 31):
continue
if len(sequence_list) < 2 or number == sequence_list[-1] + sequence_list[-2]:
sequence_list.append(number)
# Recursively check if we can extend the sequence
if backtrack(j):
return True
sequence_list.pop()
return False
# Iterate to find possible values for first two numbers
for i in range(1, string_length // 2 + 1):
#Try different starting points.
sequence_list = []
if backtrack(0):
return sequence_list
return []
Case | How to Handle |
---|---|
Empty or null input string | Return an empty list if the input string is null or empty as a Fibonacci sequence requires at least three numbers. |
Input string too short (length < 3) | Return an empty list as a valid Fibonacci sequence needs at least three numbers derived from the string. |
Input string starts with leading zeros which may cause incorrect integer conversion. | Handle leading zeros by ensuring that any number with leading zeros is equal to 0, or if greater than one digit, is not a valid option. |
Integer overflow during number parsing from the string | Check if the parsed integer exceeds the maximum value of a 32-bit signed integer after parsing, and return an empty list in that case. |
No valid Fibonacci sequence exists within the string | Return an empty list if the backtracking search completes without finding a valid Fibonacci sequence of at least three numbers. |
Multiple valid Fibonacci sequences exist; solution needs to return only one | The backtracking search finds the first valid sequence and short-circuits; subsequent possible valid sequences are not considered. |
String contains only zeros | Handle the special case of all zeros correctly forming a valid Fibonacci sequence of zeros. |
Very long input string may lead to stack overflow due to deep recursion | The problem can be structured so that the recursion depth is limited; early termination can avoid deep stack depth. |