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
๐Ÿ•ต๏ธ Decoding "123456579"1 2 3 4 5 6 5 7 9String:123456579Try:โœ“ Fibonacci Check123 + 456 = 579Valid! We found our sequence: [123, 456, 579]๐Ÿ” Other attempts that would fail:โ€ข [1, 234, ...] โ†’ 1 + 234 โ‰  next numberโ€ข [12, 34, ...] โ†’ 12 + 34 = 46, but string has "56" nextโ€ข [1234, ...] โ†’ Not enough digits left for valid sequence๐Ÿ’ก Key InsightOnce you pick the first two numbers, the entire rest of the sequence is determined!This makes backtracking very efficient.
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!
Asked in
Google 45 Facebook 32 Amazon 28 Microsoft 18
28.4K Views
Medium Frequency
~25 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen