28 / 75
Medium
Longest Consecutive Sequence
#28arrayhash-tableunion-find
Use HashSet to find sequence starts (no n-1) and count consecutive numbers in O(n).
Example:
Input:
[100,4,200,1,3,2]Output:
4 (sequence: [1,2,3,4])Common Mistakes:
- Sorting first (O(n log n) - violates O(n) requirement)
- Not checking if number is sequence start (results in O(n²))
- Using HashMap when HashSet suffices
- Not handling duplicates properly
Notes:
Key insight: only start counting from sequence beginnings. Each number visited at most twice. Time O(n), Space O(n).
💻
Java Solution Hidden
Enable “Show Full Solution” to view the code
Use HashSet to find sequence starts (no n-1) and count consecutive numbers in O(n).
Example:
Input:
[100,4,200,1,3,2]Output:
4 (sequence: [1,2,3,4])Common Mistakes:
- Sorting first (O(n log n) - violates O(n) requirement)
- Not checking if number is sequence start (results in O(n²))
- Using HashMap when HashSet suffices
- Not handling duplicates properly
Notes:
Key insight: only start counting from sequence beginnings. Each number visited at most twice. Time O(n), Space O(n).
28/75
Longest Consecutive Sequence