DeepRest

Longest Consecutive Sequence

Jul 5th, 2022 (edited)
175
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.60 KB | None | 0 0
  1. """ Why O(n) ?
  2. Since each element will be visited only twice, once in for loop and once in the while loop of its root (i.e if seq. is 2 3 4 then root of all of them is 2)
  3. Thus asymptotically linear.
  4. """
  5.  
  6. class Solution:
  7.     def longestConsecutive(self, nums: List[int]) -> int:
  8.         lookup = set(nums)
  9.         ans = 0
  10.        
  11.         for e in nums:
  12.             if e-1 in lookup:
  13.                 continue
  14.  
  15.             cnt = 0
  16.             while e in lookup:
  17.                 cnt += 1  
  18.                 e += 1
  19.                
  20.             ans = max(ans, cnt)
  21.        
  22.         return ans
Add Comment
Please, Sign In to add comment