#873
Length of Longest Fibonacci Subsequence
MediumArrayHash TableDynamic ProgrammingHash MapDynamic ProgrammingTwo Pointers
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n²) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n²)Space O(n)
The optimal solution uses dynamic programming and a hash map to efficiently find pairs of numbers that can form a Fibonacci-like sequence. This approach significantly reduces the number of checks needed.
⚙️
Algorithm
4 steps- 1Step 1: Create a hash map to store the indices of each number in the array for quick access.
- 2Step 2: Initialize a 2D array dp where dp[i][j] represents the length of the Fibonacci-like subsequence ending with arr[i] and arr[j].
- 3Step 3: Iterate through pairs of indices (i, j) and check if arr[i] + arr[j] exists in the hash map. If it does, update dp[j][k] where k is the index of arr[i] + arr[j].
- 4Step 4: Keep track of the maximum length found during the updates.
solution.py17 lines
1# Full working Python code
2from collections import defaultdict
3
4def lenLongestFibSubseq(arr):
5 index_map = {x: i for i, x in enumerate(arr)}
6 n = len(arr)
7 dp = defaultdict(int)
8 max_length = 0
9
10 for j in range(n):
11 for i in range(j):
12 if arr[j] - arr[i] in index_map:
13 k = index_map[arr[j] - arr[i]]
14 if k < i:
15 dp[i, j] = dp[k, i] + 1
16 max_length = max(max_length, dp[i, j] + 2)
17 return max_length if max_length >= 3 else 0ℹ
Complexity note: The time complexity remains O(n²) due to the nested loops. However, we use O(n) space for the hash map and the dp array, which allows for quick lookups and efficient updates.
- 1The Fibonacci-like condition requires the last two numbers to sum up to the next number, which can be efficiently checked using a hash map.
- 2Dynamic programming allows us to build solutions incrementally, storing results of subproblems to avoid redundant calculations.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.