128. Longest Consecutive Sequence ๐
Last updated
Was this helpful?
Last updated
Was this helpful?
Difficulty: Medium
- Tags: Array
, Hash Table
, Union Find
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:
Output:
Explanation: The longest consecutive elements sequence is [1, 2, 3, 4]
. Therefore, its length is 4
.
๐น Example 2:
Input:
Output:
0 <= nums.length <= 10^5
-10^9 <= nums[i] <= 10^9
To achieve an O(n)
time complexity, a HashSet
can be used to store all elements of the array. This allows us to quickly check the existence of consecutive elements.
Use HashSet for Fast Lookup:
Insert all elements into a HashSet
for O(1)
average-time checks.
Start from Sequence Beginning:
Iterate through the HashSet
.
Start counting the streak only if the current number is the start of a sequence (num - 1
is not in the set).
Count Consecutive Numbers:
Increment the count while consecutive numbers exist.
Track the Longest Streak:
Update the longest streak as needed.
O(n): Each element is processed at most twice.
O(n): Space required for the HashSet
.
You can find the full solution .