📘
Longest Consecutive Sequence
MediumArrays & Hashing
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:
100,4,200,1,3,2
Output:
4
Reasoning:
- First, we store the input values in a set for O(1) lookup:
{100, 4, 200, 1, 3, 2} - Then, we iterate over the set and check if the current number is the start of a sequence (i.e.,
num - 1is not in the set) - For each sequence start, we count the consecutive numbers:
1is a sequence start and its consecutive numbers are2,3, and4, so the sequence length is 4 - The final output is the maximum sequence length found, which is 4
Constraints:
- 0 <= len(nums) <= 10^5
- -10^9 <= nums[i] <= 10^9
Editor
Python 3.13.1
Test Results
0/0Run code to see test results.