Longest Consecutive Sequence - LeetCode 128

An Interactive Visual Explainer

Idea By: Chetan Pachpande | Executed By: Claude

← Back to Home

Longest Consecutive Sequence - LeetCode 128

Problem Description:

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 complexity.

Example: Input: nums = [100,4,200,1,3,2] → Output: 4 (sequence: [1,2,3,4])

Algorithm Complexity:

Time Complexity: O(n) - Each element is visited at most twice

Space Complexity: O(n) - HashSet to store all elements

Unprocessed
Current Element
In Current Sequence
Processed
In HashSet

Input Array

HashSet

Current Sequence

Algorithm Steps:

1. Create HashSet and add all elements from array
2. For each element, check if it's the start of a sequence (num-1 not in set)
3. If start of sequence, count consecutive numbers (num+1, num+2, ...)
4. Update maximum sequence length if current sequence is longer
5. Return the maximum sequence length found