MediumNo. 0873

Length of Longest Fibonacci Subsequence — LeetCode 873 Python Solution

Topics
Array, Hash Table, Dynamic Programming
Reading time
3 min

The problem

A sequence x1, x2, ..., xn is Fibonacci-like if: n >= 3 xi + xi+1 == xi+2 for all i + 2 <= n Given a strictly increasing array arr of positive integers forming a sequence, return the length of the longest Fibonacci-like subsequence of arr. If one does not exist, return 0.

Example

Input
arr = [1,2,3,4,5,6,7,8]
Output
5
Explanation
The longest subsequence that is fibonacci-like: [1,2,3,5,8].

Python solution

PythonSolution
class Solution:
    def lenLongestFibSubseq(self, arr: List[int]) -> int:
        n = len(arr)
        f = [[0] * n for _ in range(n)]
        d = {x: i for i, x in enumerate(arr)}
        for i in range(n):
            for j in range(i):
                f[i][j] = 2
        ans = 0
        for i in range(2, n):
            for j in range(1, i):
                t = arr[i] - arr[j]
                if t in d and (k := d[t]) < j:
                    f[i][j] = max(f[i][j], f[j][k] + 1)
                    ans = max(ans, f[i][j])
        return ans

Complexity

Time
O(n2)
Space · auxiliary
O(n2)where n is the length of the array arr

Pattern: Dynamic Programming

Define a state, write the transition, and stop recomputing the same subproblem. LeetCode 873. Length of Longest Fibonacci Subsequence is filed here because LeetCode tags it Dynamic Programming, which is the vocabulary this hub collects.

The dynamic programming guide has the Python template for the pattern and the 481 LeetCode problems that use it.

Related problems

Related problems
No.ProblemDifficulty
0139Word BreakMedium
0140Word Break IIHard
0691Stickers to Spell WordHard
0740Delete and EarnMedium
0792Number of Matching SubsequencesMedium
0823Binary Trees With FactorsMedium

Frequently asked questions

How hard is LeetCode 873. Length of Longest Fibonacci Subsequence?

LeetCode 873. Length of Longest Fibonacci Subsequence is rated Medium on LeetCode.

What is the time complexity of LeetCode 873. Length of Longest Fibonacci Subsequence?

The Python solution on this page runs in O(n2).

What is the space complexity of LeetCode 873. Length of Longest Fibonacci Subsequence?

The Python solution on this page uses O(n2), where n is the length of the array \textit{arr} auxiliary space.

What topics does LeetCode 873. Length of Longest Fibonacci Subsequence cover?

LeetCode 873. Length of Longest Fibonacci Subsequence is tagged Array, Hash Table and Dynamic Programming on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity, invisible to screen sharing.

Free to download. Check it runs on your machine, then pick a plan.