Algorithm


Problem Name: 842. Split Array into Fibonacci Sequence

 

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] < 231, (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 = "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.

 

Constraints:

  • 1 <= num.length <= 200
  • num contains only digits.
 

Code Examples

#1 Code Example with Python Programming

Code - Python Programming


class Solution:
    def splitIntoFibonacci(self, S):
        def getStarter():
            arr = []
            for i in range(1, len(S) - 1):
                for j in range(i + 1, len(S)):
                    s1, s2 = S[:i], S[i:j]
                    if (s1[0] == "0" and len(s1) > 1) or (s2[0] == "0" and len(s2) > 1): 
                        continue
                    arr.append((int(s1), int(s2), j))
            return arr                 
        def dfs(arr, i):
            if i == len(S):
                return arr
            sm = arr[-2] + arr[-1]
            l = len(str(sm))
            new = int(S[i:i + l])
            return new == sm and 0 <= sm <= mx and dfs(arr + [new], i + l)
        q, mx = getStarter(), 2 ** 31 - 1
        for p1, p2, i in q:
            seq = dfs([p1, p2], i)
            if seq:
                return seq
        return []
Copy The Code & Try With Live Editor

Input

x
+
cmd
num = "1101111"

Output

x
+
cmd
[11,0,11,11]
Advertisements

Demonstration


Previous
#841 Leetcode Keys and Rooms Solution in C, C++, Java, JavaScript, Python, C# Leetcode
Next
#843 Leetcode Guess the Word Solution in C, C++, Java, JavaScript, Python, C# Leetcode