Length of Longest Fibonacci Subsequence (LeetCode 873): Solution and Explanation
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
- Build
index, a map from each value to its position. - Create an n x n table
dpof zeros and setbest = 0. - For every k and every j < k, compute
need = arr[k] - arr[j]and look upi = index.get(need). - If
iexists andi < j, setdp[j][k] = max(dp[i][j], 2) + 1and updatebest. - Return
best. It stays 0 when no pair ever extends.
Step-by-step example
arr = [1,2,3,4,5,6,7,8]
- Pair (2, 3) needs 3 - 2 = 1, found at index 0 before 2. That starts the chain 1, 2, 3 with length 3.
- 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.
- 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.
- 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 best1class Solution {
2 public int lenLongestFibSubseq(int[] arr) {
3 int n = arr.length;
4 Map<Integer, Integer> index = new HashMap<>();
5 for (int x = 0; x < n; x++) index.put(arr[x], x);
6 int[][] dp = new int[n][n];
7 int best = 0;
8 for (int k = 0; k < n; k++) {
9 for (int j = 0; j < k; j++) {
10 int i = index.getOrDefault(arr[k] - arr[j], -1);
11 if (i >= 0 && i < j) {
12 dp[j][k] = Math.max(dp[i][j], 2) + 1;
13 best = Math.max(best, dp[j][k]);
14 }
15 }
16 }
17 return best;
18 }
19}1class Solution {
2public:
3 int lenLongestFibSubseq(vector<int>& arr) {
4 int n = arr.size();
5 unordered_map<int, int> index;
6 for (int x = 0; x < n; x++) index[arr[x]] = x;
7 vector<vector<int>> dp(n, vector<int>(n, 0));
8 int best = 0;
9 for (int k = 0; k < n; k++) {
10 for (int j = 0; j < k; j++) {
11 auto it = index.find(arr[k] - arr[j]);
12 if (it != index.end() && it->second < j) {
13 dp[j][k] = max(dp[it->second][j], 2) + 1;
14 best = max(best, dp[j][k]);
15 }
16 }
17 }
18 return best;
19 }
20};Time and space complexity
O(n^2)
There are n(n - 1) / 2 pairs, and each one does a single O(1) hash map lookup.
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.