Back to Practice Dashboard
Top 150 InterviewEasy
Longest Consecutive Sequence
Learn how to solve the 'Longest Consecutive Sequence' problem. This detailed resource details brute force and optimized approaches.
Problem Statement
Easy
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.
Write a function longestConsecutive(nums: List[int]) -> int.
Constraints
- •0 <= len(nums) <= 10^5
- •-10^9 <= nums[i] <= 10^9
Examples
Example 1
Input
nums = [100, 4, 200, 1, 3, 2]
Output
4
Explanation
The longest consecutive elements sequence is [1, 2, 3, 4]. Its length is 4.
Example 2
Input
nums = [0, 3, 7, 2, 5, 8, 4, 6, 0, 1]
Output
9
Explanation
The longest consecutive elements sequence is [0, 1, 2, 3, 4, 5, 6, 7, 8]. Its length is 9.
Need a Hint?
Analyze the input constraints. Try sorting first (O(n log n)) or using a hash map/set to track seen elements in O(n) time.
Edge Cases to Watch
- Empty list or null input variables
- Single item lists/arrays
- Extremely large input bounds causing integer or stack overflow
Ready to Solve?
Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.