Program to find length of longest fibonacci subsequence in Python

A Fibonacci-like subsequence is a sequence where each element (starting from the third) is the sum of the two preceding elements. Given a strictly increasing array, we need to find the length of the longest Fibonacci-like subsequence.

Definition

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

  • n >= 3

  • X? + X??? = X??? for all valid i

Algorithm

We'll use dynamic programming with a dictionary to track subsequence lengths ?

  • Convert array to set for O(1) lookups

  • Use a Counter to store lengths of subsequences ending at each pair (a,b)

  • For each pair (a,b), check if a+b exists to extend the sequence

  • Track the maximum length found

Example

from collections import Counter

def solve(A):
    sA = set(A)
    last = A[-1]
    B = Counter()
    best = 0
    
    for i in reversed(range(len(A))):
        a = A[i]
        for b in A[i+1:]:
            c = a + b
            if c in sA:
                B[a,b] = 1 + B[b,c]
                best = max(best, B[a,b] + 2)
            elif c > last:
                break
    
    return best

# Test with example array
A = [1, 2, 3, 4, 5, 6, 7, 8]
result = solve(A)
print(f"Length of longest Fibonacci subsequence: {result}")
Length of longest Fibonacci subsequence: 5

How It Works

For the array [1,2,3,4,5,6,7,8], the algorithm finds the subsequence [1,2,3,5,8]:

  • 1 + 2 = 3 (extends to length 3)

  • 2 + 3 = 5 (extends to length 4)

  • 3 + 5 = 8 (extends to length 5)

Step-by-Step Trace

def solve_with_trace(A):
    sA = set(A)
    last = A[-1]
    B = Counter()
    best = 0
    
    print(f"Array: {A}")
    print(f"Looking for Fibonacci-like subsequences...")
    
    for i in reversed(range(len(A))):
        a = A[i]
        for b in A[i+1:]:
            c = a + b
            if c in sA:
                B[a,b] = 1 + B[b,c]
                length = B[a,b] + 2
                best = max(best, length)
                print(f"Found: {a} + {b} = {c}, subsequence length: {length}")
            elif c > last:
                break
    
    return best

A = [1, 2, 3, 4, 5, 6, 7, 8]
result = solve_with_trace(A)
print(f"\nLongest subsequence length: {result}")
Array: [1, 2, 3, 4, 5, 6, 7, 8]
Looking for Fibonacci-like subsequences...
Found: 1 + 2 = 3, subsequence length: 3
Found: 2 + 3 = 5, subsequence length: 3
Found: 3 + 5 = 8, subsequence length: 3
Found: 1 + 2 = 3, subsequence length: 4
Found: 2 + 3 = 5, subsequence length: 4
Found: 1 + 2 = 3, subsequence length: 5

Longest subsequence length: 5

Time Complexity

The time complexity is O(n²) where n is the length of the array, as we check all pairs of elements. The space complexity is O(n) for the set and Counter storage.

Conclusion

This dynamic programming approach efficiently finds the longest Fibonacci-like subsequence by building up from smaller subsequences. The key insight is using a dictionary to store subsequence lengths for each ending pair.

Updated on: 2026-03-26T14:41:00+05:30

273 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements