imashutosh51

Longest Consecutive Sequence

Feb 5th, 2026
46
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.94 KB | None | 0 0
  1. """
  2. Store all numbers in a hash map for O(1) existence checking.
  3. For each number, only start counting if it is the beginning of a sequence (i-1 is missing).
  4. Then expand forward (i, i+1, i+2...) while numbers exist in the map and track the length.
  5. The maximum length found across all starts is the longest consecutive sequence.
  6.  
  7. Trick:
  8. When you start checking the longest consecutive elements, check for all the elements of the map because array can have a lot of the duplicates.
  9. """
  10.  
  11. class Solution:
  12.     def longestConsecutive(self, nums: List[int]) -> int:
  13.         dict={}
  14.         for i in nums:
  15.             dict[i]=dict.get(i,0)+1
  16.         ans=0
  17.         for i in dict.keys():
  18.             ele=i
  19.             if dict.get(ele-1,0)==0:
  20.                 cur=0
  21.                 while dict.get(ele,0)!=0:
  22.                     cur+=1
  23.                     ele+=1
  24.                 if cur>ans:
  25.                     ans=cur
  26.         return ans
  27.        
Advertisement
Add Comment
Please, Sign In to add comment