Split Array into Fibonacci Sequence - Problem

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³¹ (each integer fits in a 32-bit signed integer type)
  • f.length >= 3
  • f[i] + f[i + 1] == f[i + 2] for all 0 <= i < f.length - 2

Note: 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 an empty array if it cannot be done.

Input & Output

Example 1 — Valid Fibonacci Sequence
$ Input: num = "123456579"
Output: [123,456,579]
💡 Note: We can split the string as "123" + "456" + "579". Since 123 + 456 = 579, this forms a valid Fibonacci-like sequence.
Example 2 — Simple Three Numbers
$ Input: num = "11235813"
Output: [1,1,2,3,5,8,13]
💡 Note: Split as 1 + 1 = 2, 1 + 2 = 3, 2 + 3 = 5, 3 + 5 = 8, 5 + 8 = 13. Classic Fibonacci sequence.
Example 3 — No Valid Split
$ Input: num = "199100199"
Output: []
💡 Note: No way to split this string into a valid Fibonacci-like sequence of 3 or more numbers.

Constraints

  • 1 ≤ num.length ≤ 200
  • num contains only digits

Visualization

Tap to expand
Split Array into Fibonacci Sequence INPUT String of digits: 1 2 3 4 5 6 5 7 9 0 1 2 3 4 5 6 7 8 num = "123456579" Goal: Split into Fibonacci sequence where: f[i] + f[i+1] = f[i+2] f[0] + f[1] = f[2] Constraints: 0 <= f[i] < 2^31 No leading zeros, length >= 3 ALGORITHM STEPS 1 Pick First Two Numbers Try all pairs (i,j) for first two numbers in sequence 2 Calculate Expected Sum next = current + previous Check if exists in string 3 Prune Invalid Paths Skip if: leading zero, overflow, or mismatch 4 Backtrack if Needed If path fails, try next combination of splits Backtracking Tree 123 456 45.. 579 X pruned FINAL RESULT Found valid Fibonacci sequence: 123 456 579 f[0] f[1] f[2] Verification: 123 + 456 = 579 OK Length = 3 >= 3 OK No leading zeros OK Output: [123, 456, 579] String split mapping: "123" "456" "579" Key Insight: Once the first two numbers are chosen, the entire sequence is determined! Each subsequent number must equal the sum of the previous two. This enables aggressive pruning: if the expected sum doesn't match the next substring, immediately backtrack to try different first pairs. TutorialsPoint - Split Array into Fibonacci Sequence | Optimized Backtracking with Pruning
Asked in
Google 15 Facebook 12 Amazon 8
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