Longest Consecutive Sequence — LeetCode 128 Python Solution

MediumUnion FindArrayHash Table
Problem
#128
Pattern
Union-Find
Reading time
2 min

The problem

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.

Example

Input
nums = [100,4,200,1,3,2]
Output
4
Explanation
The longest consecutive elements sequence is [1, 2, 3, 4]. Therefore its length is 4.

Python solution

Python
class Solution:
    def longestConsecutive(self, nums: List[int]) -> int:
        s = set(nums)
        ans = 0
        d = defaultdict(int)
        for x in nums:
            y = x
            while y in s:
                s.remove(y)
                y += 1
            d[x] = d[y] + y - x
            ans = max(ans, d[x])
        return ans

Complexity

MeasureComplexity
TimeO(n)
SpaceO(n) auxiliary

Pattern: Union-Find

Merge groups and ask whether two things are connected, both in near-constant time. LeetCode 128. Longest Consecutive Sequence is filed here because LeetCode tags it Union Find, which is the vocabulary this hub collects.

The union-find guide has the Python template for the pattern and the 83 LeetCode problems that use it.

Related problems

On study lists

This problem is on Blind 75, NeetCode 150 and Top Interview 150.

Frequently asked questions

How hard is LeetCode 128. Longest Consecutive Sequence?
LeetCode 128. Longest Consecutive Sequence is rated Medium on LeetCode.
What is the time complexity of LeetCode 128. Longest Consecutive Sequence?
The Python solution on this page runs in O(n).
What is the space complexity of LeetCode 128. Longest Consecutive Sequence?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 128. Longest Consecutive Sequence cover?
LeetCode 128. Longest Consecutive Sequence is tagged Union Find, Array and Hash Table on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview