DEV Community

SalahElhossiny
SalahElhossiny

Posted on

3 3

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)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay