Length of Longest Fibonacci Subsequence (LeetCode 873): Solution and Explanation

Medium
Array
Hash Table
Dynamic Programming

Given a strictly increasing array of positive integers, find the longest subsequence where every term from the third on is the sum of the two before it. Return its length, or 0 if no such subsequence has at least 3 terms.

Intuition

A brute force would pick a starting pair and keep looking for the next sum, which is O(n^2 log m) and still repeats work. The useful observation is that the last two terms of a Fibonacci-like sequence fix everything before them.

If a chain ends with arr[j], arr[k], the term before arr[j] has to be arr[k] - arr[j]. Because the array is strictly increasing, that value appears at most once, so a hash map from value to index finds it in O(1).

That makes the pair (j, k) a natural DP state. The longest chain ending with (j, k) is one more than the longest chain ending with (i, j), where arr[i] = arr[k] - arr[j] and i < j.

A bare pair is not a valid answer but acts as a chain of length 2 that the first extension turns into length 3.

Approach: Pair DP with a value-to-index map

  1. Build index, a map from each value to its position.
  2. Create an n x n table dp of zeros and set best = 0.
  3. For every k and every j < k, compute need = arr[k] - arr[j] and look up i = index.get(need).
  4. If i exists and i < j, set dp[j][k] = max(dp[i][j], 2) + 1 and update best.
  5. Return best. It stays 0 when no pair ever extends.

Step-by-step example

arr = [1,2,3,4,5,6,7,8]
  1. Pair (2, 3) needs 3 - 2 = 1, found at index 0 before 2. That starts the chain 1, 2, 3 with length 3.
  2. Pair (3, 5) needs 2, found at index 1. The pair (2, 3) already has length 3, so (3, 5) gets length 4: 1, 2, 3, 5.
  3. Pair (5, 8) needs 3, found at index 2. The pair (3, 5) has length 4, so (5, 8) gets length 5: 1, 2, 3, 5, 8.
  4. No other pair beats 5, for example 1, 3, 4, 7 or 2, 3, 5, 8 have length 4, so the answer is 5.

Code: Python, Java, C++

1class Solution:
2    def lenLongestFibSubseq(self, arr: List[int]) -> int:
3        index = {x: i for i, x in enumerate(arr)}
4        n = len(arr)
5        dp = [[0] * n for _ in range(n)]
6        best = 0
7        for k in range(n):
8            for j in range(k):
9                i = index.get(arr[k] - arr[j], -1)
10                if 0 <= i < j:
11                    dp[j][k] = max(dp[i][j], 2) + 1
12                    best = max(best, dp[j][k])
13        return best
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(n^2)

There are n(n - 1) / 2 pairs, and each one does a single O(1) hash map lookup.

Space

O(n^2)

The dp table holds one length per pair. A hash map keyed by pairs only stores the pairs that actually extend.

Other approaches

Greedy walk from every starting pair (time O(n^2 log m), space O(n))

For each pair (i, j), keep computing the next sum and checking a hash set until it is missing. It is simple and fast in practice because chains grow exponentially, but the worst case is O(n^2 log m), where m is the largest value.

Two pointers instead of a map (time O(n^2), space O(n^2))

For a fixed k, move j down and i up from the two ends to find every pair with arr[i] + arr[j] = arr[k], then update dp[j][k] from dp[i][j]. It avoids hashing and has the same O(n^2) time.

Common mistakes

  • Returning 2 when nothing extends. A Fibonacci-like sequence needs at least 3 terms, so the answer must be 0.
  • Accepting an index i that is not before j. arr[k] - arr[j] may exist in the array but sit at or after j, which would break the order.
  • Starting every dp value at 0 and adding 1 directly. A pair that has not been extended should count as length 2, hence max(dp[i][j], 2) + 1.
  • Iterating j in the outer loop and k in the inner loop with the wrong order. dp[i][j] must be final before dp[j][k] reads it, which holds when k is the outer loop.

Frequently asked questions

Why is the chain state a pair and not a single index?

One term does not determine the next one: 5 could be followed by 8 (after 3) or by 9 (after 4). Two consecutive terms fix the whole sequence, so the pair is the smallest state that works.

Why is the lookup unique?

The array is strictly increasing, so every value appears once. There is at most one index i with arr[i] = arr[k] - arr[j].

Can the answer be larger than about 45?

No. The terms grow at least as fast as the Fibonacci numbers, and with values up to 10^9 a Fibonacci-like sequence of positive integers has at most about 45 terms.

Does arr[k] - arr[j] < arr[j] need its own check?

It is implied by i < j: values before index j are smaller than arr[j]. Checking i < j covers it.