Longest Consecutive Sequence - Solution
Solutions and explanations

class Solution:
    def longestConsecutive(self, nums: List[int]) -> int:
        nums_set = set(nums)
        max_length = 0
        for num in nums_set:
            if num - 1 not in nums_set: # ie. num becomes start of a sequence
                length = 1
                while num + length in nums_set:
                    length += 1
                max_length = max(max_length, length)
        return max_length

Complexity Analysis

Here, n is the length of the input.

  • Time Complexity: O(n)

    • Building Hashset: O(n) as each element is traversed once during building the hashset.
    • Sequence Lookup: O(n) as sequence lookup is triggered only for the start of sequences, so each element in the input is scanned at most twice during sequence lookup.
  • Space Complexity: O(n)- the hashset takes O(n) extra space.