Program to find length of longest Fibonacci subsequence from a given list in Python

Given a list of strictly increasing positive numbers, we need to find the length of the longest Fibonacci-like subsequence. A Fibonacci-like subsequence has at least 3 elements where each element equals the sum of the two preceding elements: A[i] = A[i-1] + A[i-2].

For example, if the input is nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14], the output will be 6 because we can form the subsequence [1, 2, 3, 5, 8, 13].

Algorithm

The approach uses a brute force method with the following steps:

  • Convert the input list to a set for O(1) lookup operations
  • For each pair of elements (i, j) where i < j, treat them as the first two elements of a potential Fibonacci sequence
  • Calculate the next element as the sum of current two elements
  • Continue building the sequence while the next element exists in the original list
  • Track the maximum length found

Implementation

class Solution:
    def solve(self, nums):
        A = nums
        n = len(A)
        maxLen = 0
        S = set(A)
        
        for i in range(0, n):
            for j in range(i + 1, n):
                x = A[j]
                y = A[i] + A[j]
                length = 2
                
                while y in S:
                    z = x + y
                    x = y
                    y = z
                    length += 1
                    maxLen = max(maxLen, length)
        
        if maxLen > 2:
            return maxLen
        else:
            return 0

# Test the solution
ob = Solution()
nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
result = ob.solve(nums)
print(f"Longest Fibonacci subsequence length: {result}")
Longest Fibonacci subsequence length: 6

How It Works

Let's trace through the algorithm with a smaller example [1, 2, 3, 5, 8]:

def trace_fibonacci_subsequence(nums):
    n = len(nums)
    S = set(nums)
    maxLen = 0
    
    print(f"Input: {nums}")
    print(f"Set for lookup: {S}")
    print()
    
    for i in range(n):
        for j in range(i + 1, n):
            x = nums[j]
            y = nums[i] + nums[j]
            length = 2
            sequence = [nums[i], nums[j]]
            
            print(f"Starting with pair: {nums[i]}, {nums[j]}")
            
            while y in S:
                sequence.append(y)
                z = x + y
                x = y
                y = z
                length += 1
                print(f"  Found {sequence[-1]}, sequence: {sequence}")
            
            if length > maxLen:
                maxLen = length
                print(f"  New max length: {maxLen}")
            print()
    
    return maxLen

# Test with smaller example
nums = [1, 2, 3, 5, 8]
result = trace_fibonacci_subsequence(nums)
print(f"Final result: {result}")
Input: [1, 2, 3, 5, 8]
Set for lookup: {1, 2, 3, 5, 8}

Starting with pair: 1, 2
  Found 3, sequence: [1, 2, 3]
  Found 5, sequence: [1, 2, 3, 5]
  Found 8, sequence: [1, 2, 3, 5, 8]
  New max length: 5

Starting with pair: 1, 3

Starting with pair: 1, 5

Starting with pair: 1, 8

Starting with pair: 2, 3
  Found 5, sequence: [2, 3, 5]
  Found 8, sequence: [2, 3, 5, 8]

Starting with pair: 2, 5

Starting with pair: 2, 8

Starting with pair: 3, 5
  Found 8, sequence: [3, 5, 8]

Starting with pair: 3, 8

Starting with pair: 5, 8

Final result: 5

Time and Space Complexity

  • Time Complexity: O(n² × L) where n is the length of input and L is the average length of Fibonacci subsequences
  • Space Complexity: O(n) for the set storage

Conclusion

This algorithm efficiently finds the longest Fibonacci-like subsequence by using a set for fast lookups and checking all possible starting pairs. The approach works well for moderately sized inputs and returns 0 if no valid subsequence of length ? 3 is found.

---
Updated on: 2026-03-25T12:35:13+05:30

435 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements