I'm doing leetcode 128 (longest consecutive sequence). This is the problem: problem picture
I wrote 2 working solutions, both using DFS.
The 1st solution uses lrucache to cache the DFS function
The 2nd solution uses a dictionary to do the same thing (I think).
Solution 1 is significantly faster (~500ms vs ~4000ms) but I don't really understand why. To my understanding, they are essentially doing the same thing. What am I missing?
Here are the 2 solutions:
Solution 1 (LRU Cache) (Faster):
def longestConsecutive(self, nums: List[int]) -> int:
graph = dict()
for num in nums:
graph[num] = num+1
@functools.lru_cache(maxsize = None)
def dfs(num):
if num in graph:
return 1 + dfs(graph[num])
return 0
longest = 0
for num in nums:
longest = max(longest, dfs(num))
return longest
Solution 2 (Dictionary Lookup) (Slower):
def longestConsecutive(self, nums: List[int]) -> int:
graph = dict()
for num in nums:
graph[num] = num+1
def dfs(num):
if num in graph:
return 1 + dfs(graph[num])
return 0
longest = 0
for num in nums:
if num-1 not in graph:
longest = max(longest, dfs(num))
return longest