#842

Split Array into Fibonacci Sequence

Medium
StringBacktrackingBacktrackingRecursion
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

The optimal solution leverages backtracking with early stopping conditions to efficiently explore potential splits while adhering to Fibonacci sequence rules. This reduces unnecessary checks and improves performance.

⚙️

Algorithm

4 steps
  1. 1Step 1: Use a backtracking function to explore all possible splits of the string.
  2. 2Step 2: Maintain a path to store the current Fibonacci sequence being built.
  3. 3Step 3: For each split, check if the current number can be part of the Fibonacci sequence based on the last two numbers.
  4. 4Step 4: If a valid sequence is found, return it; otherwise, backtrack and try the next split.
solution.py22 lines
1# Full working Python code
2
3def splitIntoFibonacci(num):
4    def backtrack(start, path):
5        if start == len(num) and len(path) >= 3:
6            return path
7        for i in range(start + 1, len(num) + 1):
8            if num[start] == '0' and i > start + 1:
9                break
10            num1 = int(num[start:i])
11            if num1 >= 2**31:
12                break
13            if len(path) >= 2 and num1 != path[-1] + path[-2]:
14                continue
15            path.append(num1)
16            result = backtrack(i, path)
17            if result:
18                return result
19            path.pop()
20        return []
21
22    return backtrack(0, [])

Complexity note: The optimal solution runs in O(n) time because it explores each character in the string once, and the space complexity is O(n) due to the storage of the Fibonacci sequence.

  • 1The sequence must start with non-zero numbers unless it's a single zero.
  • 2Each number must not exceed 2^31 - 1.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.