← Back to DSA Animator
Longest Consecutive Sequence LC #128 Medium HashSet
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 1
Input: nums = [100,4,200,1,3,2]
Output: 4
Explanation: The longest consecutive sequence is [1,2,3,4] with length 4.
Constraints: 0 ≤ nums.length ≤ 10⁵  |  −10⁹ ≤ nums[i] ≤ 10⁹  |  Must run in O(n)
Try Examples
Custom:
Approach
HashSet — Find Sequence Starts
Add all numbers to a HashSet. A sequence 'start' is a number with no predecessor (num-1 not in set). From each start, count how far the consecutive chain extends. Each number is visited at most twice — O(n).
Array
Variables
cur (num)
streak len
maxLen
isStart?
Step Logic
Press ▶ Play or Next Step to begin.
🎉
Ready
0 / 0
Select an example above and press Play.
Algorithm
1
Add all numbers to a HashSet for O(1) lookup
2
Find sequence starts: nums where (num−1) is not in set
3
From each start, count consecutive run using set.contains(cur+1)
4
Track and return maxLen across all streaks
Time
O(n)
Space
O(n)
Why It Works

By storing all numbers in a HashSet, we get O(1) contains checks. We only start counting from a number that has no predecessor — this guarantees we never recount the same sequence from the middle. Even though there is a while loop inside the for loop, each number is touched at most twice total, keeping the overall complexity O(n).