Split Array Into Fibonacci Sequence Problem
Description
LeetCode Problem 842.
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, and
- f[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.
Return any Fibonacci-like sequence split from num, or return [] if it cannot be done.
Example 1:
Input: num = "123456579"
Output: [123,456,579]
Example 2:
Input: num = "11235813"
Output: [1,1,2,3,5,8,13]
Example 3:
Input: num = "112358130"
Output: []
Explanation: The task is impossible.
Example 4:
Input: num = "0123"
Output: []
Explanation: Leading zeroes are not allowed, so "01", "2", "3" is not valid.
Example 5:
Input: num = "1101111"
Output: [11,0,11,11]
Explanation: The output [11, 0, 11, 11] would also be accepted.
Constraints:
- 1 <= num.length <= 200
- num contains only digits.
Solution
Approach: Try the First Two Numbers, Then Follow
A Fibonacci-like sequence is completely determined by its first two numbers: every later number must be the sum of the two before it. So there is no need for a general search over all ways to cut the string. Choose the first two numbers, and the rest of the split is forced.
- For every length of the first number, and every length of the second number:
- Starting right after the second number, repeatedly compute
next = a + band check that the string continues with exactly the digits ofnext. If it does, append it and move past those digits; if not, this choice fails. - The first choice that consumes the whole string is an answer. If none does, return
[].
Three rules prune the choices and keep the answer valid:
- 32-bit limit. Stop extending a number once it exceeds 231 − 1, and reject a sequence as soon as a sum does. So each of the first two numbers has at most 10 digits.
- Leading zeros. If the first (or second) number starts with
0, the only allowed value is0itself, so do not try longer lengths for it. Later numbers are written from their value, so they never have leading zeros. - At least three numbers. The second number must end before the last digit, so at least one more number follows it.
Building each candidate number digit by digit (value * 10 + digit) avoids parsing very long substrings, which would overflow.
Complexity: O(n) time, since there are at most 10 · 10 choices for the first two numbers and each check scans the string once, and O(n) space for the sequence, where n is the length of num.
LIMIT = 2 ** 31 - 1 # every number must fit in a 32-bit signed integer
class Solution:
def splitIntoFibonacci(self, num: str) -> List[int]:
n = len(num)
first = 0
# The first two numbers decide the whole sequence, so try every choice for them.
for first_end in range(1, n): # first = num[0:first_end]
first = first * 10 + int(num[first_end - 1])
if first > LIMIT:
break
second = 0
for second_end in range(first_end + 1, n): # second = num[first_end:second_end]
second = second * 10 + int(num[second_end - 1])
if second > LIMIT:
break
sequence = self.follow(num, first, second, second_end)
if sequence:
return sequence
if num[first_end] == "0":
break # the second number is "0" and cannot have more digits
if num[0] == "0":
break # the first number is "0" and cannot have more digits
return []
def follow(self, num, first, second, pos):
# Every next number is forced: it must be first + second, written at pos.
sequence = [first, second]
while pos < len(num):
nxt = sequence[-2] + sequence[-1]
if nxt > LIMIT:
return []
text = str(nxt)
if not num.startswith(text, pos):
return []
sequence.append(nxt)
pos += len(text)
return sequence # at least 3 numbers, since the second one ended before the last digit
Now write it from memory
Close the write-up and solve it yourself against the tests.