DEV Community

SalahElhossiny
SalahElhossiny

Posted on

Leetcode Solutions: Longest Consecutive Sequence

Given an unsorted array of integers nums, return the length of the longest consecutive elements sequence.

You must write an algorithm that runs in O(n) time.

class Solution(object):
    def longestConsecutive(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """

        nums, res, t = list(set(nums)), 0, 0
        heapq.heapify(nums)

        while nums:
            pop_val = heapq.heappop(nums)
            t += 1
            if nums == [] or nums[0] != pop_val + 1:
                res = max(t, res)
                t = 0
        return res




Enter fullscreen mode Exit fullscreen mode

Top comments (0)