Formatted question description: https://leetcode.ca/all/842.html

842. Split Array into Fibonacci Sequence

Level

Medium

Description

Given a string S of digits, such as S = "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^31 - 1, (that is, each integer fits a 32-bit signed integer type);
  • F.length >= 3;
  • and F[i] + F[i+1] = F[i+2] for all 0 <= i < F.length - 2.

Also, 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 S, or return [] if it cannot be done.

Example 1:

Input: “123456579”

Output: [123,456,579]

Example 2:

Input: “11235813”

Output: [1,1,2,3,5,8,13]

Example 3:

Input: “112358130”

Output: []

Explanation: The task is impossible.

Example 4:

Input: “0123”

Output: []

Explanation: Leading zeroes are not allowed, so “01”, “2”, “3” is not valid.

Example 5:

Input: “1101111”

Output: [110, 1, 111]

Explanation: The output [11, 0, 11, 11] would also be accepted.

Note:

  1. 1 <= S.length <= 200
  2. S contains only digits.

Solution

First check the maximum end index of the first number and the second number. Suppose the string contains only three numbers that form a Fibonacci-like sequence, then the third number can’t be shorter than either the first number of the second number. Suppose the length of string S is length, then the maximum end index of the first number is length / 2 - 1 and the maximum end index of the second number is length * 2 / 3 - 1.

For each possible choice of the first number and the second number, try to form a Fibonacci-like sequence starting from the first number and the second number. If one choice can lead to a Fibonacci-like sequence that equals S, return a list containing all the numbers in the sequence. Otherwise, return an empty list.

class Solution {
    public List<Integer> splitIntoFibonacci(String S) {
        List<Integer> list = new ArrayList<Integer>();
        if (S == null || S.length() == 0)
            return list;
        int length = S.length();
        int firstMax = Math.min(length / 2, 10), secondMax = Math.min(length * 2 / 3, 20);
        for (int i = 1; i <= firstMax; i++) {
            if (i > 1 && S.charAt(0) == '0' || Long.parseLong(S.substring(0, i)) > Integer.MAX_VALUE)
                break;
            int secondMaxUpper = Math.min(secondMax, i + 11);
            for (int j = i + 1; j <= secondMaxUpper; j++) {
                List<Integer> splitIndices = new ArrayList<Integer>();
                String firstNumStr = S.substring(0, i);
                String secondNumStr = S.substring(i, j);
                splitIndices.add(i);
                splitIndices.add(j);
                if (secondNumStr.length() > 1 && secondNumStr.charAt(0) == '0')
                    break;
                StringBuffer sb = new StringBuffer(firstNumStr + secondNumStr);
                int prevIndex = j;
                while (sb.length() < length) {
                    long firstNum = Long.parseLong(firstNumStr);
                    long secondNum = Long.parseLong(secondNumStr);
                    long sum = firstNum + secondNum;
                    if (sum > Integer.MAX_VALUE)
                        break;
                    String sumStr = String.valueOf(sum);
                    sb.append(sumStr);
                    int index = prevIndex + sumStr.length();
                    if (index < length)
                        splitIndices.add(index);
                    prevIndex = index;
                    firstNumStr = secondNumStr;
                    secondNumStr = sumStr;
                }
                if (sb.toString().equals(S)) {
                    int size = splitIndices.size();
                    for (int k = size - 1; k >= 0; k--) {
                        int splitIndex = splitIndices.get(k);
                        sb.insert(splitIndex, ',');
                    }
                    String[] array = sb.toString().split(",");
                    int sequenceLength = array.length;
                    for (int k = 0; k < sequenceLength; k++)
                        list.add(Integer.parseInt(array[k]));
                    return list;
                }
            }
        }
        return list;
    }
}

All Problems

All Solutions