Longest Consecutive Sequence – Python 3 (Week 12 – 04)

  class Solution:
    def longestConsecutive(self, nums: List[int]) -> int:
        if len(nums) < 1:
            return 0
        
        numsSet = set()
        for num in nums:
            numsSet.add(num)
        
        ans = 1
        for num in nums:
            if num in numsSet:
                numsSet.remove(num)                
                l = num - 1
                r = num + 1            
                while l in numsSet:
                    numsSet.remove(l)
                    l -= 1
                while r in numsSet:
                    numsSet.remove(r)
                    r += 1
                ans = max(ans, r - l - 1)
            
        return ans

Time O(n). Space O(n). n is len(nums).

Leave a comment

Design a site like this with WordPress.com
Get started