algoadvance

Leetcode 873. Length of Longest Fibonacci Subsequence

Problem Statement

Given a strictly increasing array arr of positive integers forming a sequence, you need to find the length of the longest Fibonacci-like subsequence of arr. If one does not exist, return 0.

A Fibonacci-like sequence is a sequence X such that:

For example, [1, 3, 7, 11, 12, 14, 18] can form the Fibonacci-like sequence [1, 11, 12, 23].

Example

Clarifying Questions

Strategy

To find the length of the longest Fibonacci-like subsequence, we will use dynamic programming along with hashing:

  1. Create a map that maps each element to its index for quick lookup.
  2. Use a 2D DP array where dp[i][j] represents the length of the Fibonacci-like subsequence that ends with arr[i] and arr[j].
  3. Iterate through pairs of indices (i, j) and for each pair, use the map to find if there exists a previous element arr[k] such that arr[k] + arr[i] = arr[j].
  4. Update the DP table accordingly.
  5. Keep track of the maximum length found during the process.

Code

import java.util.HashMap;
import java.util.Map;

public class LengthOfLongestFibonacciSubsequence {
    public int lenLongestFibSubseq(int[] arr) {
        int n = arr.length;
        Map<Integer, Integer> indexMap = new HashMap<>();
        for (int i = 0; i < n; i++) {
            indexMap.put(arr[i], i);
        }

        int[][] dp = new int[n][n];
        int maxLen = 0;

        for (int j = 0; j < n; j++) {
            for (int i = 0; i < j; i++) {
                int k = indexMap.getOrDefault(arr[j] - arr[i], -1);
                if (k >= 0 && k < i) {
                    dp[i][j] = dp[k][i] + 1;
                    maxLen = Math.max(maxLen, dp[i][j] + 2);
                }
            }
        }

        return maxLen > 2 ? maxLen : 0;
    }

    public static void main(String[] args) {
        LengthOfLongestFibonacciSubsequence solver = new LengthOfLongestFibonacciSubsequence();
        int[] arr = {1, 2, 3, 4, 5, 6, 7, 8};
        System.out.println(solver.lenLongestFibSubseq(arr)); // Output: 5
    }
}

Time Complexity

This approach efficiently finds the length of the longest Fibonacci-like subsequence in polynomial time.

Cut your prep time in half and DOMINATE your interview with AlgoAdvance AI