KatInterview

872. Split Array into Fibonacci Sequence

MediumSolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

The problem asks us to split a string of digits into a Fibonacci-like sequence. A key challenge is that we don't know the lengths of the numbers in the sequence beforehand. This ambiguity points towards a search algorithm, and backtracking is a natural fit for exploring all possible partitions of the string.

Solution

Split Array into Fibonacci Sequence in Python

class Solution:
    def splitIntoFibonacci(self, num: str) -> List[int]:
        result = []
        n = len(num)
        
        def backtrack(index):
            # Base case: if we've reached the end, check for sequence length
            if index == n:
                return len(result) >= 3

            current_num = 0
            for i in range(index, n):
                # Build the current number
                current_num = current_num * 10 + int(num[i])

                # Pruning: leading zeros
                if num[index] == '0' and i > index:
                    break
                
                # Pruning: integer overflow (Python handles large ints, but problem specifies 32-bit)
                if current_num >= 2**31:
                    break
                
                size = len(result)
                if size >= 2:
                    # Check Fibonacci property
                    if current_num > result[size - 2] + result[size - 1]:
                        break # Too large, prune
                    if current_num < result[size - 2] + result[size - 1]:
                        continue # Too small, need more digits
                
                # Add candidate and recurse
                result.append(current_num)
                if backtrack(i + 1):
                    return True
                
                # Backtrack
                result.pop()
            
            return False

        backtrack(0)
        return result

Split Array into Fibonacci Sequence in Java

class Solution {
    public List<Integer> splitIntoFibonacci(String num) {
        List<Integer> result = new ArrayList<>();
        backtrack(num, result, 0);
        return result;
    }

    private boolean backtrack(String num, List<Integer> result, int index) {
        // Base case: If we've reached the end of the string, check if we have a valid sequence.
        if (index == num.length()) {
            return result.size() >= 3;
        }

        long currentNum = 0;
        for (int i = index; i < num.length(); i++) {
            // Build the current number from the substring.
            currentNum = currentNum * 10 + (num.charAt(i) - '0');

            // Pruning: handle leading zeros. A number can be '0', but not '01', '02' etc.
            if (num.charAt(index) == '0' && i > index) {
                break;
            }

            // Pruning: number must not exceed 32-bit signed int max value.
            if (currentNum > Integer.MAX_VALUE) {
                break;
            }

            int size = result.size();
            if (size >= 2) {
                long sum = (long) result.get(size - 2) + result.get(size - 1);
                if (currentNum > sum) {
                    // currentNum is too large, and will only get larger. Prune this path.
                    break;
                }
                if (currentNum < sum) {
                    // currentNum is too small, need more digits. Continue the loop.
                    continue;
                }
                // If currentNum == sum, it's a potential candidate.
            }

            // If we reach here, it's a valid candidate for the current position.
            result.add((int) currentNum);

            // Recurse to the next part of the string.
            if (backtrack(num, result, i + 1)) {
                return true; // Solution found, propagate true up the call stack.
            }

            // Backtrack: remove the number and try another possibility.
            result.remove(result.size() - 1);
        }

        return false;
    }
}

Split Array into Fibonacci Sequence in C++

class Solution {
public:
    vector<int> splitIntoFibonacci(string num) {
        vector<int> result;
        backtrack(num, result, 0);
        return result;
    }

private:
    bool backtrack(const string& num, vector<int>& result, int index) {
        // Base case: If we've reached the end of the string, check if we have a valid sequence.
        if (index == num.length()) {
            return result.size() >= 3;
        }

        long long current_num = 0;
        for (int i = index; i < num.length(); ++i) {
            // Pruning: handle leading zeros. A number can be '0', but not '01', '02' etc.
            if (num[index] == '0' && i > index) {
                break;
            }

            current_num = current_num * 10 + (num[i] - '0');

            // Pruning: number must not exceed 32-bit signed int max value.
            if (current_num > INT_MAX) {
                break;
            }

            int size = result.size();
            if (size >= 2) {
                long long sum = (long long)result[size - 2] + result[size - 1];
                if (current_num > sum) {
                    // current_num is too large, and will only get larger. Prune this path.
                    break;
                }
                if (current_num < sum) {
                    // current_num is too small, need more digits. Continue the loop.
                    continue;
                }
                // If current_num == sum, it's a potential candidate.
            }

            // If we reach here, it's a valid candidate for the current position.
            result.push_back(current_num);

            // Recurse to the next part of the string.
            if (backtrack(num, result, i + 1)) {
                return true; // Solution found, propagate true up the call stack.
            }

            // Backtrack: remove the number and try another possibility.
            result.pop_back();
        }

        return false;
    }
};

Split Array into Fibonacci Sequence in TypeScript

function splitIntoFibonacci(num: string): number[] {
    const result: number[] = [];
    const n = num.length;

    function backtrack(index: number): boolean {
        // Base case: if we've reached the end, check for sequence length
        if (index === n) {
            return result.length >= 3;
        }

        let currentNum = 0;
        for (let i = index; i < n; i++) {
            // Build the current number
            currentNum = currentNum * 10 + parseInt(num[i]);

            // Pruning: leading zeros
            if (num[index] === '0' && i > index) {
                break;
            }

            // Pruning: integer overflow (JS numbers are 64-bit float, check against 32-bit int max)
            if (currentNum >= 2**31) {
                break;
            }

            const size = result.length;
            if (size >= 2) {
                const sum = result[size - 2] + result[size - 1];
                if (currentNum > sum) {
                    break; // Too large, prune
                }
                if (currentNum < sum) {
                    continue; // Too small, need more digits
                }
            }

            // Add candidate and recurse
            result.push(currentNum);
            if (backtrack(i + 1)) {
                return true;
            }

            // Backtrack
            result.pop();
        }

        return false;
    }

    backtrack(0);
    return result;
}

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.