Leetcode

128.longestConsecutiveSequence.py

class Solution:
    def longestConsecutive(self, nums: List[int]) -> int:
        n = set()

        for num in nums:
            n.add(num)
        
        longest = 0
        
        for i in range(len(nums)):
            count = 0
            low, high = None, None
            if nums[i] in n:
                count += 1
                low = nums[i] - 1
                high = nums[i] + 1
            
            while low in n:
                n.remove(low)
                count += 1
                low -=1
            
            while high in n:
                n.remove(high)
                count += 1
                high += 1
            longest = max(count, longest)
        
        return longest