Super easy python using set


  • 0
    W

    Idea is to keep a set and popping one element from it at a time. After an element X is popped, we can subsequently check for other elements in that group. Either in the smaller than X group or bigger than X group. Update the longest at end of loop.

    def longestConsecutive(self, nums):
        S = set(nums)
        ret = 0
        while nums:
            val = nums.pop()
            counter = 1
            s, b = val - 1, val + 1
            while s in S:
                S.remove(s)
                counter += 1
                s -= 1
            while b in S:
                S.remove(b)
                counter += 1
                b += 1
            ret = max(ret, counter)
        return ret

Log in to reply
 

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