KatInterview

905. Length of Longest Fibonacci Subsequence

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 for the length of the longest Fibonacci-like subsequence in a given strictly increasing array of positive integers. A Fibonacci-like sequence is defined by the property that each term (from the third term onwards) is the sum of the two preceding terms, i.e., x_i + x_{i+1} = x_{i+2}. The sequence must have at least three elements.

Solution

Length of Longest Fibonacci Subsequence in Python

import collections

class Solution:
    def lenLongestFibSubseq(self, arr: List[int]) -> int:
        n = len(arr)
        if n <= 2:
            return 0

        # Map to store value to its index for O(1) lookup.
        val_to_index = {val: i for i, val in enumerate(arr)}

        # dp[(i, j)] will store the length of the Fibonacci-like subsequence
        # ending with arr[i] and arr[j].
        # Using a dictionary for sparse DP table, default length for any pair is 2.
        dp = collections.defaultdict(lambda: 2)
        maxLength = 0

        for j in range(n):
            for i in range(j):
                # Find the previous element required: prev = arr[j] - arr[i]
                prev = arr[j] - arr[i]
                
                # Check if prev exists in the array and its index is less than i.
                if prev in val_to_index and val_to_index[prev] < i:
                    k = val_to_index[prev]
                    # We found a valid triplet. Extend the sequence ending at (k, i).
                    # The length of sequence ending at (k, i) is dp[(k, i)].
                    # If not set, defaultdict gives 2. So new length is 2 + 1 = 3.
                    # If set, it's an existing F-subsequence, new length is dp[(k,i)]+1.
                    dp[(i, j)] = dp[(k, i)] + 1
                
                # We don't need an else case because defaultdict initializes to 2.
                # However, we only care about lengths > 2 for the final result.
                # To find maxLength, we must consider all computed lengths.
                maxLength = max(maxLength, dp[(i, j)])

        # The result must have length >= 3.
        return maxLength if maxLength > 2 else 0

Length of Longest Fibonacci Subsequence in Java

class Solution {
    public int lenLongestFibSubseq(int[] arr) {
        int n = arr.length;
        if (n <= 2) {
            return 0;
        }

        // Map to store value to its index for O(1) lookup.
        Map<Integer, Integer> valToIndex = new HashMap<>();
        for (int i = 0; i < n; i++) {
            valToIndex.put(arr[i], i);
        }

        // dp[i][j] will store the length of the Fibonacci-like subsequence
        // ending with arr[i] and arr[j].
        int[][] dp = new int[n][n];
        int maxLength = 0;

        for (int j = 1; j < n; j++) {
            for (int i = 0; i < j; i++) {
                // Find the previous element required: prev = arr[j] - arr[i]
                int prev = arr[j] - arr[i];

                // Check if prev exists in the array and its index is less than i.
                // We need k < i < j for arr[k], arr[i], arr[j] to be a valid subsequence.
                // Because arr is strictly increasing, prev < arr[i] implies k < i.
                Integer k = valToIndex.get(prev);
                if (k != null && k < i) {
                    // We found a valid triplet. Extend the sequence ending at (k, i).
                    // The length of sequence ending at (k, i) is dp[k][i].
                    // By our logic, if (k, i) is a base pair, dp[k][i] is 2.
                    // So the new length is dp[k][i] + 1.
                    dp[i][j] = dp[k][i] + 1;
                } else {
                    // If no such previous element exists, this pair (arr[i], arr[j])
                    // forms a potential F-subsequence of length 2.
                    dp[i][j] = 2;
                }
                maxLength = Math.max(maxLength, dp[i][j]);
            }
        }

        // The result must have length >= 3.
        return maxLength > 2 ? maxLength : 0;
    }
}

Length of Longest Fibonacci Subsequence in C++

class Solution {
public:
    int lenLongestFibSubseq(vector<int>& arr) {
        int n = arr.size();
        if (n <= 2) {
            return 0;
        }

        // Map to store value to its index for O(1) lookup.
        unordered_map<int, int> val_to_index;
        for (int i = 0; i < n; ++i) {
            val_to_index[arr[i]] = i;
        }

        // dp[i][j] will store the length of the Fibonacci-like subsequence
        // ending with arr[i] and arr[j].
        vector<vector<int>> dp(n, vector<int>(n, 0));
        int maxLength = 0;

        for (int j = 1; j < n; ++j) {
            for (int i = 0; i < j; ++i) {
                // Find the previous element required: prev = arr[j] - arr[i]
                int prev = arr[j] - arr[i];

                // Check if prev exists in the array and its index is less than i.
                // We need k < i < j for arr[k], arr[i], arr[j] to be a valid subsequence.
                // Because arr is strictly increasing, prev < arr[i] implies k < i.
                if (prev < arr[i] && val_to_index.count(prev)) {
                    int k = val_to_index[prev];
                    // We found a valid triplet. Extend the sequence ending at (k, i).
                    // The length of sequence ending at (k, i) is dp[k][i].
                    // If dp[k][i] is 0, it means (k, i) is a base pair, length 2.
                    // So the new length is (2) + 1 = 3.
                    // If dp[k][i] > 2, it's an existing F-subsequence, length dp[k][i].
                    // So new length is dp[k][i] + 1.
                    // We can unify this logic by initializing all pairs to length 2.
                    dp[i][j] = dp[k][i] + 1;
                } else {
                    // If no such previous element exists, this pair (arr[i], arr[j])
                    // forms a potential F-subsequence of length 2.
                    dp[i][j] = 2;
                }
                maxLength = max(maxLength, dp[i][j]);
            }
        }

        // The result must have length >= 3.
        return maxLength > 2 ? maxLength : 0;
    }
};

Length of Longest Fibonacci Subsequence in TypeScript

function lenLongestFibSubseq(arr: number[]): number {
    const n = arr.length;
    if (n <= 2) {
        return 0;
    }

    // Map to store value to its index for O(1) lookup.
    const valToIndex = new Map<number, number>();
    for (let i = 0; i < n; i++) {
        valToIndex.set(arr[i], i);
    }

    // dp[i][j] will store the length of the Fibonacci-like subsequence
    // ending with arr[i] and arr[j].
    const dp: number[][] = Array(n).fill(0).map(() => Array(n).fill(0));
    let maxLength = 0;

    for (let j = 1; j < n; j++) {
        for (let i = 0; i < j; i++) {
            // Find the previous element required: prev = arr[j] - arr[i]
            const prev = arr[j] - arr[i];

            // Check if prev exists in the array and its index is less than i.
            if (valToIndex.has(prev)) {
                const k = valToIndex.get(prev)!;
                if (k < i) {
                    // We found a valid triplet. Extend the sequence ending at (k, i).
                    // The length of sequence ending at (k, i) is dp[k][i].
                    // By our logic, if (k, i) is a base pair, dp[k][i] will be 2.
                    dp[i][j] = dp[k][i] + 1;
                } else {
                    dp[i][j] = 2;
                }
            } else {
                // If no such previous element exists, this pair (arr[i], arr[j])
                // forms a potential F-subsequence of length 2.
                dp[i][j] = 2;
            }
            maxLength = Math.max(maxLength, dp[i][j]);
        }
    }

    // The result must have length >= 3.
    return maxLength > 2 ? maxLength : 0;
}

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.