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, andf[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 <= 200num contains only digits.This approach uses backtracking to recursively split the string into all potential combinations of integers and checks if they form a valid Fibonacci sequence.
This Python code implements a backtracking solution to split the input string into potential Fibonacci sequences.
backtrack is defined to recursively attempt to form a sequence.JavaScript
Time Complexity: O(2^n), since each combination of splitting points is considered recursively.
Space Complexity: O(n), for the recursion stack and the result list.
This approach involves iteratively parsing possible substrings and dynamically checking for valid Fibonacci sequences.
This Java code uses an iterative method to find Fibonacci-like sequences.
isValid function checks if extending the sequence remains valid.C#
Time Complexity: O(n^3), due to nested loops exploring potential splits and sequence validity.
Space Complexity: O(n), primarily to store intermediate sequence results.
| Approach | Complexity |
|---|---|
| Backtracking and Recursion | Time Complexity: O(2^n), since each combination of splitting points is considered recursively. Space Complexity: O(n), for the recursion stack and the result list. |
| Iterative Parsing with Dynamic Updates | Time Complexity: O(n^3), due to nested loops exploring potential splits and sequence validity. Space Complexity: O(n), primarily to store intermediate sequence results. |
Split Array Largest Sum - Leetcode 410 - Python • NeetCode • 99,331 views views
Watch 9 more video solutions →Practice Split Array into Fibonacci Sequence with our built-in code editor and test cases.
Practice on FleetCodePractice this problem
Open in Editor