I have just solved https://leetcode.com/problems/length-of-longest-fibonacci-subsequence/. The objective is to find the longest Fibonacci sub-sequence in an array of strictly increasing integers.
I need some help figuring out the difference in time and space complexity between my solution and the "optimal" one that I got off the solutions section of leetcode.
1- My algorithm:
class Solution:
def lenLongestFibSubseq(self, A):
dp = [collections.defaultdict(int) for i in range(len(A))]
res = 2
for j in range(len(A)):
for i in range(j):
prev = dp[i].get(A[j], 0)
prev = 2 if not prev else prev+1
dp[j][A[j]+A[i]] = prev
res = max(res, prev)
return res if res > 2 else 0
2- "Optimal" algorithm:
class Solution:
def lenLongestFibSubseq(self, A):
dp = collections.defaultdict(int)
s = set(A)
for j in range(len(A)):
for i in range(j):
if A[j] - A[i] < A[i] and A[j] - A[i] in s:
dp[A[i], A[j]] = dp.get((A[j] - A[i], A[i]), 2) + 1
return max(dp.values() or [0])
Time complexity is easy --> they are both O(n^2)
For space complexity I think both are O(n^2)
at least mine is for sure, since for each index I maintain a dict whose size is equal to index-1
.
However the "optimal" algorithm seems like it is O(n^2)
space too since he is caching one value for all pairs [A[i], A[j]]
.
I am here because the online judge rates my solution as 4 times slower 2000ms
vs 500ms
and 3 times as space consuming 45Mb
vs 15Mb
. I might be missing something big, any help is welcome.