Split Array into Fibonacci Sequence - Problem
Imagine you have a string of digits like "123456579" and you want to split it into a Fibonacci-like sequence where each number is the sum of the two previous numbers: [123, 456, 579] (because 123 + 456 = 579).
Your task is to find any valid way to split the given string into such a sequence, following these rules:
- Each number must fit in a 32-bit signed integer (0 โค number < 231)
- The sequence must have at least 3 numbers
- For every three consecutive numbers:
f[i] + f[i+1] = f[i+2] - No leading zeros allowed (except for the number "0" itself)
Return any valid Fibonacci-like sequence as an array, or an empty array [] if impossible.
Input & Output
example_1.py โ Basic Fibonacci Split
$
Input:
num = "1101111"
โบ
Output:
[1, 1, 2, 3, 5, 8, 13]
๐ก Note:
Split as [1,1,2,3,5,8,13] where each number equals the sum of the previous two: 1+1=2, 1+2=3, 2+3=5, 3+5=8, 5+8=13
example_2.py โ Larger Numbers
$
Input:
num = "123456579"
โบ
Output:
[123, 456, 579]
๐ก Note:
Split as [123,456,579] because 123 + 456 = 579. This is a valid 3-number Fibonacci sequence.
example_3.py โ Impossible Case
$
Input:
num = "11235813"
โบ
Output:
[]
๐ก Note:
No valid split exists. While this looks like Fibonacci digits, there's no way to split it into a valid sequence with the given constraints.
Constraints
- 1 โค num.length โค 200
- num contains only digits
- Each number in sequence must be < 231
- No leading zeros except for number "0" itself
Visualization
Tap to expand
Understanding the Visualization
1
Try First Break
Place the first break to separate the first number. Try lengths 1, 2, 3...
2
Try Second Break
For each first number, try different positions for the second break
3
Follow the Pattern
Once you have two numbers, the Fibonacci rule determines where all other breaks must be
4
Validate or Backtrack
If the pattern works for the entire string, you found the answer. Otherwise, try the next possibility
Key Takeaway
๐ฏ Key Insight: In a Fibonacci sequence, the first two numbers completely determine all the rest. This constraint makes backtracking much more efficient than it might initially appear!
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code