smj007

longest consecutive sequence

Apr 24th, 2025
362
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.80 KB | None | 0 0
  1. # average tc: O(n), worst case tc: O(n*n) - because of hash collisions it can happen
  2. # that the worst case of hash look up is O(n)
  3.  
  4. class Solution:
  5.     def longestConsecutive(self, nums: List[int]) -> int:
  6.  
  7.         hashset = set()
  8.         longest_streak = 0
  9.  
  10.         for num in nums:
  11.             hashset.add(num)
  12.  
  13.         for i in range(len(nums)):
  14.             # check if that it is the greatest number in neighbouring
  15.             if nums[i] + 1 not in hashset:
  16.                 current_streak = 1
  17.                 current_num = nums[i]
  18.                 # keep checking untill you reach an endpoint
  19.                 while current_num-1 in hashset:
  20.                     current_streak += 1
  21.                     current_num -= 1
  22.  
  23.                 longest_streak = max(longest_streak, current_streak)
  24.  
  25.         return longest_streak
Advertisement
Add Comment
Please, Sign In to add comment