Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # average tc: O(n), worst case tc: O(n*n) - because of hash collisions it can happen
- # that the worst case of hash look up is O(n)
- class Solution:
- def longestConsecutive(self, nums: List[int]) -> int:
- hashset = set()
- longest_streak = 0
- for num in nums:
- hashset.add(num)
- for i in range(len(nums)):
- # check if that it is the greatest number in neighbouring
- if nums[i] + 1 not in hashset:
- current_streak = 1
- current_num = nums[i]
- # keep checking untill you reach an endpoint
- while current_num-1 in hashset:
- current_streak += 1
- current_num -= 1
- longest_streak = max(longest_streak, current_streak)
- return longest_streak
Advertisement
Add Comment
Please, Sign In to add comment