Longest Consecutive Sequence - 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.

A consecutive sequence is a sequence of integers where each number is exactly one more than the previous number.

Input & Output

Example 1 — Mixed Numbers
$ Input: nums = [100,4,200,1,3,2]
Output: 4
💡 Note: The longest consecutive elements sequence is [1,2,3,4], which has length 4
Example 2 — Duplicates
$ Input: nums = [0,3,7,2,5,8,4,6,0,1]
Output: 9
💡 Note: The longest consecutive sequence is [0,1,2,3,4,5,6,7,8] with length 9
Example 3 — Single Element
$ Input: nums = [9]
Output: 1
💡 Note: Single element forms a sequence of length 1

Constraints

  • 0 ≤ nums.length ≤ 105
  • -109 ≤ nums[i] ≤ 109

Visualization

Tap to expand
Longest Consecutive Sequence INPUT Unsorted Array nums[] 100 4 200 1 3 2 [0] [1] [2] [3] [4] [5] Hash Set Created: {100, 4, 200, 1, 3, 2} O(1) lookup for each number n = 6 elements ALGORITHM STEPS 1 Build Hash Set Add all nums to set O(n) 2 Find Sequence Starts Check if (num-1) NOT in set 3 Extend Each Sequence Count while (num+1) in set 4 Track Maximum Update longest length found Sequence Detection: 100: (99 not in set) --> Start! Count: 1 1: (0 not in set) --> Start! 1-->2-->3-->4 Count: 4 200: (199 not in set) Count: 1 FINAL RESULT Longest Consecutive Sequence: 1 2 3 4 Output: 4 OK - Length = 4 Time: O(n) Space: O(n) Key Insight: By using a Hash Set, we achieve O(1) lookups. We only start counting from sequence beginnings (numbers without a predecessor in the set). This ensures each number is visited at most twice, giving us O(n) total time complexity instead of O(n log n) from sorting approaches. TutorialsPoint - Longest Consecutive Sequence | Hash Set Optimal Approach
Asked in
Google 45 Facebook 38 Amazon 32 Microsoft 28
78.0K Views
High Frequency
~25 min Avg. Time
1.9K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen