Longest Consecutive Sequence

Array
Hard

Approach

Diagrams

Analysis

Time

O(n)

Space

O(n)
class Solution:
    def longestConsecutive(self, nums):
        nums = set(nums)

        longestSoFar = 0
        lengthRightNow = 0

        for firstNumInSequence in nums:
            isUsedInPrevSequence = firstNumInSequence - 1 in nums

            if isUsedInPrevSequence:
                continue

            lengthRightNow = 1
            nextNumInSequence = firstNumInSequence + 1

            while nextNumInSequence in nums:
                lengthRightNow += 1
                nextNumInSequence += 1

            longestSoFar = max(longestSoFar, lengthRightNow)

        return longestSoFar

Learn

#Array

#Hash Set

Videos