Longest Consecutive Sequence
Longest Consecutive Sequence is LeetCode 128 (Medium). You are given an unsorted integer array nums and must return the length of the longest run of consecutive integers whose values all appear in the array. GFG lists the same task as Longest Consecutive Subsequence.
- The values can come from anywhere in the array; their positions do not matter, only whether each value is present.
- Repeated values count once. A run never uses the same value twice.
- An empty array has answer 0.
The array holds up to 10⁵ numbers, each between −10⁹ and 10⁹. The problem asks for an O(n) algorithm, which rules out sorting, and the value range rules out a counting array indexed by value.
- 0 <= nums.length <= 10⁵
- -10⁹ <= nums[i] <= 10⁹
Intuition
Picture the values on a number line. They form separate blocks of consecutive integers, and the answer is the size of the biggest block.
A hash set answers "is v present?" in O(1), so you can walk a block from one end: from n, ask for n + 1, n + 2, and so on until one is missing. Walking from every value, though, re-walks each block many times: a block of length k is walked from all k of its values.
The fix is to walk only from the left end of each block, the values n whose n − 1 is missing. Every block has exactly one left end, so each block is walked once.
When a problem is about runs of consecutive values (not consecutive positions) in an unsorted array and wants better than sorting, put the values in a hash set and only start a walk where the previous value is missing. The same trick counts runs of consecutive days, IDs or seat numbers.
Approach
Before reading on, explain why the while loop inside the for loop does not make this O(n²). Count how many times each value can be stepped over by that inner loop.
Two ways to solve it
Put every value in a set, and only count forward from values whose left neighbour is missing.
- Work: each value is stepped over once.
- Memory: the set, up to n values.
- Meets: the O(n) the problem asks for.
The answer interviewers want in the end.
Sort the numbers, then walk once, growing a run while each value is one more than the last.
- Work: the sort dominates.
- Memory: a sorted copy, no set.
- Trap: skip equal neighbours.
Simple, and a fine first answer, but slower than O(n).
Both are common answers. The hash set is the only one that meets the O(n) requirement, so the steps, code and live demo below follow it; the sorting code comes after the demo.
Build the set
seen = set(nums). Repeats collapse into one entry, which is right because a repeated value never makes a run longer, and every membership test becomes O(1) on average.
Find the starts
For each value n in the set, check n - 1. If it is present, n is inside a run that starts further left: skip it. If it is absent, n starts a run.
Walk each run once
From a start, set length = 1 and increase it while n + length is in the set. When the next value is missing, the run is over; update best = max(best, length).
Why it is correct
Every maximal run of consecutive values has exactly one smallest value, and that value is the only one with no predecessor in the set. So every run is measured in full exactly once, and the largest measurement is the answer.
Code in Python, C++ and Java
Sort, then scan
After sorting, consecutive values sit side by side. cur counts the run ending at index i: it grows when nums[i] is one more than the value before, stays put on a repeat, and restarts at 1 on a gap.
Common pitfalls
Walking forward from every value
for n in seen:
length = 1
while n + length in seen:
length += 1for n in seen:
if n - 1 in seen:
continue
length = 1
while n + length in seen:
length += 1Without the start check, a run of length k is walked from all k of its values, k(k+1)/2 steps. On range(10⁵) that is about 5 · 10⁹ lookups and a time-out.
Looping over nums instead of the set
for n in nums:
if n - 1 in seen:
continuefor n in seen:
if n - 1 in seen:
continueIf a run's start appears many times in nums, every copy passes the start check and walks the whole run again. An input of 50,000 copies of 0 followed by 1 to 50,000 makes about 2.5 · 10⁹ steps. The set holds each value once.
Counting repeats in a sorted scan
if nums[i] == nums[i - 1] + 1:
cur += 1
else:
cur = 1if nums[i] == nums[i - 1]:
continue
if nums[i] == nums[i - 1] + 1:
cur += 1
else:
cur = 1In the sorting approach, [1, 2, 2, 3] must give 3. Treating the second 2 as a break resets the run; equal neighbours have to be skipped, not counted and not treated as a gap.
Edge cases
The set is empty, the loop never runs, and best stays 0.
Complexity
n - 1 per distinct value. The inner while runs only from run starts, and each start walks its own run, so across the whole loop it steps over each value once, not once per start. That is at most about 3n average-O(1) lookups. The set holds up to n values.Longest Consecutive Sequence FAQ
Does the order of iterating over the set matter?
No. Whatever order the set yields values in, a non-start is skipped in O(1) and each start walks its whole run. The total work and the answer are the same.
Can a hash set make this slow in the worst case?
Lookups are O(1) on average. Adversarial inputs that collide in the hash table can degrade them, which is why the bound is stated as average O(n). In practice, with Python's integer hashing or Java's HashSet, it runs in linear time.