Longest Consecutive Sequence (LeetCode 128): Solution and Explanation
Given an unsorted array of integers, return the length of the longest run of consecutive values, such as 1, 2, 3, 4, that all appear in the array. The values do not need to be adjacent in the input, and the solution should run in linear time.
Watch it run step by step
Try your own input and write the code →Intuition
If you sort the array, consecutive values line up next to each other and one scan finds the longest run. That is O(n log n), and the problem asks for O(n), so sorting is out. Without sorting, the natural tool for "is the value x + 1 present?" is a hash set, which answers in constant time. So a first idea is: for every number, keep checking n + 1, n + 2 and so on in the set and count how far you get.
That idea has a hidden cost. For the run 1, 2, 3, 4, it counts 4 steps from 1, then 3 steps from 2, then 2 from 3 and 1 from 4. A single long run of length n would cost O(n²) work, because every element re-walks the rest of its run. The fix is to only count from the beginning of a run. A number n starts a run exactly when n - 1 is not in the set. Every other number is in the middle of some run and will be covered when you count from that run's start.
With that rule, each run is walked once from its start, so the total number of set lookups across all runs is proportional to the number of distinct values. The loop over elements does one extra lookup each to test n - 1, which is also linear. The answer is the longest length you counted.
Approach: Hash set and sequence starts
- Build
numSet = set(nums)for constant time membership checks, and setlongest = 0. - Loop over each
ninnums. - If
n - 1is innumSet, skipn; it is not the start of a run. - Otherwise set
length = 0and keep incrementing it whilen + lengthis innumSet. - Update
longest = max(length, longest). - Return
longestafter the loop.
Step-by-step example
nums = [100, 4, 200, 1, 3, 2]
- numSet = {100, 4, 200, 1, 3, 2}.
- n = 100: 99 is not in the set, so 100 starts a run. 101 is missing, so length = 1 and longest = 1.
- n = 4: 3 is in the set, so skip.
- n = 200: 199 is missing, so it starts a run of length 1. longest stays 1.
- n = 1: 0 is missing, so count 1, 2, 3 and 4, all present; 5 is missing. length = 4 and longest = 4.
- n = 3 and n = 2 both have their predecessor in the set and are skipped. Return 4.
Code: Python, Java, C++
1class Solution:
2 def longestConsecutive(self, nums: List[int]) -> int:
3 numSet = set(nums)
4 longest = 0
5
6 for n in nums:
7 # Check if it's the start of a sequence
8 if (n - 1) not in numSet:
9 length = 0
10 while (n + length) in numSet:
11 length += 1
12 longest = max(length, longest)
13
14 return longest1class Solution {
2 public int longestConsecutive(int[] nums) {
3 Set<Integer> numSet = new HashSet<>();
4 for (int num : nums) numSet.add(num);
5
6 int longest = 0;
7
8 for (int n : nums) {
9 if (!numSet.contains(n - 1)) {
10 int length = 0;
11 while (numSet.contains(n + length)) {
12 length++;
13 }
14 longest = Math.max(longest, length);
15 }
16 }
17 return longest;
18 }
19}1class Solution {
2public:
3 int longestConsecutive(vector<int>& nums) {
4 unordered_set<int> numSet(nums.begin(), nums.end());
5 int longest = 0;
6
7 for (int n : nums) {
8 if (!numSet.count(n - 1)) {
9 int length = 0;
10 while (numSet.count(n + length)) {
11 length++;
12 }
13 longest = max(longest, length);
14 }
15 }
16 return longest;
17 }
18};Time and space complexity
O(n)
Building the set is O(n). Each element does one lookup for n - 1, and the inner while loop only runs from run starts, so across all distinct starts it advances through each value once. One caveat: because the outer loop walks nums rather than numSet, a run start that appears many times is recounted each time; looping over the set removes that edge case.
O(n)
The hash set stores up to n distinct values.
Other approaches
Sort and scan (time O(n log n), space O(1) to O(n))
Sort the array, then walk it once, extending the current run when the next value is exactly one larger, ignoring duplicates, and resetting otherwise. It is simple and uses little memory but violates the linear time requirement.
Union-find (time O(n α(n)), space O(n))
Treat each value as a node and union it with n + 1 when present. The largest component size is the answer. It is near linear but much more code than the set approach.
Common mistakes
- Counting forward from every number instead of only from run starts. That turns the algorithm quadratic on inputs like a long sorted range.
- Iterating over
numswhen it contains many copies of a run start. Each copy restarts the count; iterating overnumSetavoids the repeated work. - Returning 1 for an empty array. With no elements there is no sequence, so the answer is 0, which the
longest = 0initialization handles. - Sorting and then forgetting to skip duplicates, so [1, 2, 2, 3] incorrectly resets the run at the second 2.
Frequently asked questions
How is Longest Consecutive Sequence O(n) when there is a nested loop?
The inner while loop only runs for numbers whose predecessor is missing, and it walks each run exactly once. Summed over all runs, the inner loop does at most n steps in total, so the whole algorithm stays linear.
Why check whether n - 1 is in the set?
It identifies the smallest element of a run. Counting only from there guarantees each run is measured once instead of once per element.
Can I just sort the array?
Sorting gives a correct O(n log n) solution and is fine when the linear requirement is relaxed. Remember to skip duplicates while scanning.
Do duplicates break the hash set approach?
No. The set stores each value once, so duplicates do not change any run length. They can only cause repeated counting if you iterate over the original array.