Finding Fibonacci sequence in an array using JavaScript

In JavaScript, finding the longest Fibonacci subsequence in an array involves identifying a sequence where each element is the sum of the two preceding ones. This is a dynamic programming problem that requires careful tracking of potential Fibonacci sequences.

Fibonacci Sequence Definition

A sequence X?, X?, ..., X? is Fibonacci if:

  • n ? 3 (at least 3 elements)

  • X? + X??? = X??? for all valid i (each element equals sum of previous two)

Problem Statement

Given an array of numbers, find the length of the longest Fibonacci subsequence. A subsequence maintains the original order but can skip elements.

Example:

Input: [1, 3, 7, 11, 14, 25, 39]
Output: 5
Explanation: Longest sequence is [3, 11, 14, 25, 39]

Solution Approach

We use dynamic programming with a 2D memoization table. For each pair of elements, we track the length of the Fibonacci sequence ending with that pair.

Array: [1, 3, 7, 11, 14, 25, 39] 3 11 14 25 39 3+11=14 11+14=25 14+25=39 Algorithm Steps: 1. Create hash map for O(1) element lookup 2. Initialize 2D memo table for DP 3. For each pair (i,j), check if (arr[j]-arr[i]) exists before i 4. Update memo[i][j] = memo[prev][i] + 1 5. Track maximum length found

Implementation

const arr = [1, 3, 7, 11, 14, 25, 39];

const longestFibonacci = (arr = []) => {
    // Create hash map for O(1) lookup
    const map = arr.reduce((acc, num, index) => {
        acc[num] = index;
        return acc;
    }, {});
    
    // Initialize 2D memoization table
    const memo = arr.map(() => arr.map(() => 0));
    let max = 0;
    
    // Check every pair of elements
    for(let i = 0; i < arr.length; i++) {
        for(let j = i + 1; j < arr.length; j++) {
            const a = arr[i];
            const b = arr[j];
            const diff = b - a;
            
            // Check if the previous element (b-a) exists before index i
            if(map.hasOwnProperty(diff) && map[diff] < i) {
                const prevIndex = map[diff];
                memo[i][j] = memo[prevIndex][i] + 1;
            }
            
            max = Math.max(max, memo[i][j]);
        }
    }
    
    // Return length (+2 for the first two elements of the sequence)
    return max > 0 ? max + 2 : 0;
};

console.log("Array:", arr);
console.log("Longest Fibonacci subsequence length:", longestFibonacci(arr));
Array: [1, 3, 7, 11, 14, 25, 39]
Longest Fibonacci subsequence length: 5

How It Works

The algorithm uses dynamic programming with these key insights:

  • Hash Map: Provides O(1) lookup to check if a required element exists

  • 2D Memo Table: memo[i][j] stores the length of Fibonacci sequence ending with elements at indices i and j

  • Pair Processing: For each pair (arr[i], arr[j]), checks if arr[j] - arr[i] exists before index i

  • Length Calculation: Adds 2 to account for the first two elements of the sequence

Time Complexity

Operation Complexity Explanation
Hash Map Creation O(n) Single pass through array
Nested Loops O(n²) Check all pairs of elements
Overall O(n²) Efficient for this problem type

Conclusion

This dynamic programming solution efficiently finds the longest Fibonacci subsequence using memoization and hash mapping. The O(n²) time complexity makes it suitable for moderately sized arrays while maintaining clear, readable code structure.

Updated on: 2026-03-15T23:19:00+05:30

666 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements