Easy Python solution, cannot believe this is hard (Medium at most if not easy)


  • 0
    Y
    class Solution(object):
        def longestConsecutive(self, nums):
            """
            :type nums: List[int]
            :rtype: int
            """
            num_set = set(nums)
            max_len = 0
            blackout = set()
            for n in nums:
                if n in blackout:
                    continue
                l, r = n - 1, n + 1
                counter = 1
                blackout.add(n)
                while l in num_set or r in num_set:
                    if l in num_set:
                        counter += 1
                        blackout.add(l)
                        l -= 1
                    if r in num_set:
                        counter += 1
                        blackout.add(r)
                        r += 1
                max_len = max(max_len, counter)
            
            return max_len
    

    This is a common technique to have O(1) access to list elements using a dict or set.
    Then all you need to do is seeding from one number and get consecutive sequences, black them out and continue


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.