0

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.

d_darric
  • 387
  • 2
  • 15
  • Write palce to ask code review questions is [codereview stackexchange](https://codereview.stackexchange.com) – shaik moeed Jul 06 '19 at 11:16
  • 1
    4 or 3 times faster is usually not a difference in time complexity but in some constants. I think it's because that `if` statement that decrease the amount of `dp.get` and keeps some of the array empty which might activate some optimizations in the background. – Yonlif Jul 06 '19 at 15:26

0 Answers0