Split Array into Fibonacci Sequence

Updated on 25 June, 2025
Split Array into Fibonacci Sequence header image

Problem Statement

In the given task, the objective is to dissect a string containing digits into a sequence that mirrors the properties of a Fibonacci sequence—where each number is the sum of the two preceding ones. These extracted sequences must adhere strictly to certain conditions:

  • Each number in the sequence must be representable as a 32-bit signed integer.
  • The sequence should contain a minimum of three numbers.
  • Each sequence part should conform to the Fibonacci rule, specifically, the third number should be the sum of the first two and so forth.
  • A sequence part cannot begin with extra zeros unless the part itself is zero. The challenge expects a solution to either return such a Fibonacci-like sequence extracted from the provided string, or an empty sequence when such extraction is not feasible.

Examples

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 <= 200
  • num contains only digits.

Approach and Intuition

This problem can be approached by carefully partitioning the input string into valid numeric blocks and repeatedly checking the Fibonacci condition. The constraints and assumptions outlined suggest the following approach:

  1. Analyze the string in chunks that might form potential Fibonacci sequence starters.

  2. Starting with the smallest possible valid number, generate possible sequences and validate them:

    • For each chosen pair of starting numbers in the sequence, simulate the generation of the next numbers based exclusively on the Fibonacci-like summing property.
    • For every new number, check if it matches the start of the remaining unprocessed portion of the string.
    • Continue this process until either the entire string is consumed by the sequence or it becomes impossible to continue the sequence based on the remainder of the string.
  3. Consider practical boundaries for searches based on string length and possible integer sizes (32-bit restriction).

  4. Cycle through potential starting pairs with careful attention to the rules regarding leading zeros.

Given the indicated constraints (string length up to 200 characters):

  • The choice of starting block sizes must be managed efficiently because the possible combinations grow exponentially with longer strings.
  • Use a loop through the string to pick a starting number, then a nested loop for the second number, and check if continuing the pattern could exhaust the string correctly. If a valid sequence satisfying all conditions is found, it should be returned immediately. If no sequences are found after exhausting all pairs, return an empty list.

The edge cases, such as strings that contain a series of zeros, or strings that are too short to form a sequence, should be handled from the outset to prevent unnecessary computation.

Solutions

  • Java
java
class Solution {
    public List<Integer> generateFibonacciSequence(String input) {
        int length = input.length();
        for (int i = 0; i < Math.min(10, length); ++i) {
            if (input.charAt(0) == '0' && i > 0) break;
            long firstNum = Long.parseLong(input.substring(0, i+1));
            if (firstNum >= Integer.MAX_VALUE) break;

            outerLoop: for (int j = i+1; j < Math.min(i+10, length); ++j) {
                if (input.charAt(i+1) == '0' && j > i+1) break;
                long secondNum = Long.parseLong(input.substring(i+1, j+1));
                if (secondNum >= Integer.MAX_VALUE) break;

                List<Integer> fibSequence = new ArrayList<>();
                fibSequence.add((int) firstNum);
                fibSequence.add((int) secondNum);

                int nextIndex = j + 1;
                while (nextIndex < length) {
                    long nextNum = fibSequence.get(fibSequence.size() - 2) + fibSequence.get(fibSequence.size() - 1);
                    String nextNumStr = String.valueOf(nextNum);

                    if (nextNum <= Integer.MAX_VALUE && input.substring(nextIndex).startsWith(nextNumStr)) {
                        nextIndex += nextNumStr.length();
                        fibSequence.add((int) nextNum);
                    }
                    else continue outerLoop;
                }
                if (fibSequence.size() >= 3) return fibSequence;
            }
        }

        return new ArrayList<Integer>();
    }
}

The provided Java code details a method designed to generate a Fibonacci Sequence from a given string input. The method generateFibonacciSequence parses the string attempting to construct a valid sequence adhering to Fibonacci properties where each number is the sum of the previous two.

Here's how the code operates:

  1. Initializes the process by iterating through potential starting numbers in the string. If the string begins with a '0', it promptly ignores any number starting with '0' except "0" itself. It handles the number parsing with a Long to manage potentially large values that are within the bounds of Integer.MAX_VALUE.

  2. For each valid starting number, another nested loop identifies the second number in the sequence. It continues the same checks for leading zeros and size constraints as the first number.

  3. Upon identifying both a valid first and second number, it initiates an ArrayList to store the potential Fibonacci sequence, firmly adding the first two numbers.

  4. The algorithm then continually attempts to compute the next number in the sequence by summing the last two numbers of the current sequence and checking it against the subsequent segment of the input string.

  5. If the next number also conforms to the Fibonacci criteria and matches the input sequence, it's added to the array. This process loops until there are no more characters in the input string matching the Fibonacci condition.

  6. If at any point the sequence computation fails to align with Fibonacci rules, it breaks out of the sequence calculation and moves to the next potential start pair of numbers.

  7. Return the Fibonacci sequence if it contains at least three numbers, confirming a valid Fibonacci sequence. Otherwise, an empty list is returned, indicating no valid sequence was found.

This solution effectively checks for and constructs a Fibonacci sequence by validating each sequential number against a strict set of criteria including input alignment, numerical overflow, and the Fibonacci numerical property.

Comments

No comments yet.