Practice · 01 Unsorted Arrays: Hashing · 4/4
Longest Consecutive Sequence
The longest run of consecutive numbers, in O(n) without sorting.
Understand the problem
A family of several people wants to sit together on a flight. The booking system gives you the seat numbers still free in one row of a wide aircraft, in no particular order: [100, 4, 200, 1, 3, 2]. What's the longest run of free seats with consecutive numbers? Here it's 1, 2, 3, 4: four seats side by side.
The problem, stripped of the plane:
Given an unsorted array of integers
nums, return the length of the longest sequence of consecutive values (like 1, 2, 3, 4). The values don't need to be next to each other in the array. Your algorithm must run in O(n) time.
| Input | Output | The run |
|---|---|---|
[100, 4, 200, 1, 3, 2] | 4 | 1, 2, 3, 4 |
[0, 3, 7, 2, 5, 8, 4, 6, 0, 1] | 9 | 0 to 8 (the second 0 adds nothing) |
[1, 0, 1, 2] | 3 | 0, 1, 2 |
[] | 0 | no numbers, no run |
The limits on LeetCode: 0 to 100,000 numbers, each between -10⁹ and 10⁹.
Brute force first
For every number x, count upwards: is x + 1 in the array? x + 2? Stop at the first missing one. Searching the array each time is a full scan.
int longestConsecutiveBrute(const vector<int>& nums) {
int best = 0;
for (int x : nums) {
int length = 1;
while (find(nums.begin(), nums.end(), (long long)x + length) != nums.end()) // O(n) search
length++;
best = max(best, length);
}
return best;
}static int longestConsecutiveBrute(int[] nums) {
int best = 0;
for (int x : nums) {
int length = 1;
while (contains(nums, (long) x + length)) length++; // O(n) search every time
best = Math.max(best, length);
}
return best;
}
static boolean contains(int[] nums, long v) {
for (int y : nums) if (y == v) return true;
return false;
}def longest_consecutive_brute(nums):
best = 0
for x in nums:
length = 1
while x + length in nums: # list search: O(n) every time
length += 1
best = max(best, length)
return bestfunction longestConsecutiveBrute(nums) {
let best = 0;
for (const x of nums) {
let length = 1;
while (nums.includes(x + length)) length++; // array search: O(n) every time
best = Math.max(best, length);
}
return best;
}func longestConsecutiveBrute(nums []int) int {
best := 0
for _, x := range nums {
length := 1
for slices.Contains(nums, x+length) { // O(n) search every time
length++
}
best = max(best, length)
}
return best
}static int LongestConsecutiveBrute(int[] nums)
{
int best = 0;
foreach (int x in nums)
{
int length = 1;
while (nums.Contains(x + length)) length++; // array search: O(n) every time
best = Math.Max(best, length);
}
return best;
}That's up to n starting points, each walking up to n steps, each step scanning n values: O(n³) in the worst case. For 100,000 numbers that's hopeless.
A better middle step: sort first
Sort the numbers, then walk once: if a number is exactly one more than the previous, the run grows; if it's equal, skip it (a duplicate); otherwise a new run starts.
int longestConsecutiveSorted(vector<int> nums) { // by value: sorts a copy
if (nums.empty()) return 0;
sort(nums.begin(), nums.end());
int best = 1, run = 1;
for (size_t i = 1; i < nums.size(); i++) {
if (nums[i] == nums[i - 1]) continue; // duplicate: run neither grows nor breaks
run = ((long long)nums[i] == (long long)nums[i - 1] + 1) ? run + 1 : 1;
best = max(best, run);
}
return best;
}static int longestConsecutiveSorted(int[] nums) {
if (nums.length == 0) return 0;
int[] a = nums.clone();
Arrays.sort(a);
int best = 1, run = 1;
for (int i = 1; i < a.length; i++) {
if (a[i] == a[i - 1]) continue; // duplicate: run neither grows nor breaks
run = ((long) a[i] == (long) a[i - 1] + 1) ? run + 1 : 1;
best = Math.max(best, run);
}
return best;
}def longest_consecutive_sorted(nums):
if not nums:
return 0
a = sorted(nums)
best = run = 1
for i in range(1, len(a)):
if a[i] == a[i - 1]:
continue # duplicate: run neither grows nor breaks
run = run + 1 if a[i] == a[i - 1] + 1 else 1
best = max(best, run)
return bestfunction longestConsecutiveSorted(nums) {
if (nums.length === 0) return 0;
const a = [...nums].sort((x, y) => x - y); // numeric sort, not the default text sort
let best = 1, run = 1;
for (let i = 1; i < a.length; i++) {
if (a[i] === a[i - 1]) continue; // duplicate: run neither grows nor breaks
run = a[i] === a[i - 1] + 1 ? run + 1 : 1;
best = Math.max(best, run);
}
return best;
}func longestConsecutiveSorted(nums []int) int {
if len(nums) == 0 {
return 0
}
a := slices.Clone(nums)
slices.Sort(a)
best, run := 1, 1
for i := 1; i < len(a); i++ {
if a[i] == a[i-1] {
continue // duplicate: run neither grows nor breaks
}
if a[i] == a[i-1]+1 {
run++
} else {
run = 1
}
best = max(best, run)
}
return best
}static int LongestConsecutiveSorted(int[] nums)
{
if (nums.Length == 0) return 0;
var a = (int[])nums.Clone();
Array.Sort(a);
int best = 1, run = 1;
for (int i = 1; i < a.Length; i++)
{
if (a[i] == a[i - 1]) continue; // duplicate: run neither grows nor breaks
run = ((long)a[i] == (long)a[i - 1] + 1) ? run + 1 : 1;
best = Math.Max(best, run);
}
return best;
}O(n log n): fast enough to pass on LeetCode, but it breaks the problem's O(n) rule. In an interview, this is a good second answer, and the interviewer will ask for the last step.
See it in a diagram
Put every number in a hash set, so "is y there?" is O(1). Now, the brute force wasted work by counting the same run from every member: from 1 it walks 1-2-3-4, from 2 it walks 2-3-4 again, and so on. The fix: only start counting from the beginning of a run, a number whose left neighbour x - 1 is not in the set.
Every run is walked exactly once, from its start.
Spot the pattern
The hashing signal again: unsorted, and you need "is this value present?" fast. What's new is the guard: before doing expensive work from an element, check a cheap condition (x - 1 absent) that makes sure the work is done once per group instead of once per member.
That "only start from the beginning" idea comes back often: counting islands only from an unvisited cell, building chains only from a head node. Whenever many elements would redo the same walk, find the one element that should own it.
The optimal solution
- Put all numbers into a set
present(this also removes duplicates). - For each
xin the set:- if
x - 1is in the set, skip it: it's in the middle of a run; - otherwise, walk
x + 1,x + 2, … while they're in the set, and count the length.
- if
- Keep the longest length seen. Return it (0 for an empty input).
Code in 6 languages
Each program runs the first two examples and the empty array.
#include <algorithm>
#include <cstdio>
#include <unordered_set>
#include <vector>
using namespace std;
int longestConsecutive(const vector<int>& nums) {
unordered_set<long long> present(nums.begin(), nums.end());
int best = 0;
for (long long x : present) { // the set, so each value once
if (present.count(x - 1)) continue; // not a start: x - 1 will count this run
int length = 1;
while (present.count(x + length)) length++; // walk up from the start
best = max(best, length);
}
return best;
}
int main() {
vector<vector<int>> tests = {{100, 4, 200, 1, 3, 2}, {0, 3, 7, 2, 5, 8, 4, 6, 0, 1}, {}};
for (auto& nums : tests) {
printf("[");
for (size_t i = 0; i < nums.size(); i++) printf(i ? ", %d" : "%d", nums[i]);
printf("] -> %d\n", longestConsecutive(nums));
}
}import java.util.*;
public class Main {
static int longestConsecutive(int[] nums) {
Set<Long> present = new HashSet<>();
for (int x : nums) present.add((long) x);
int best = 0;
for (long x : present) { // the set, so each value once
if (present.contains(x - 1)) continue; // not a start: x - 1 will count this run
int length = 1;
while (present.contains(x + length)) length++; // walk up from the start
best = Math.max(best, length);
}
return best;
}
public static void main(String[] args) {
int[][] tests = {{100, 4, 200, 1, 3, 2}, {0, 3, 7, 2, 5, 8, 4, 6, 0, 1}, {}};
for (int[] nums : tests)
System.out.println(Arrays.toString(nums) + " -> " + longestConsecutive(nums));
}
}def longest_consecutive(nums):
present = set(nums)
best = 0
for x in present: # the set, so each value once
if x - 1 in present:
continue # not a start: x - 1 will count this run
length = 1
while x + length in present: # walk up from the start
length += 1
best = max(best, length)
return best
tests = [[100, 4, 200, 1, 3, 2], [0, 3, 7, 2, 5, 8, 4, 6, 0, 1], []]
for nums in tests:
print(nums, "->", longest_consecutive(nums))function longestConsecutive(nums) {
const present = new Set(nums);
let best = 0;
for (const x of present) { // the set, so each value once
if (present.has(x - 1)) continue; // not a start: x - 1 will count this run
let length = 1;
while (present.has(x + length)) length++; // walk up from the start
best = Math.max(best, length);
}
return best;
}
const tests = [[100, 4, 200, 1, 3, 2], [0, 3, 7, 2, 5, 8, 4, 6, 0, 1], []];
for (const nums of tests)
console.log(`[${nums.join(", ")}] -> ${longestConsecutive(nums)}`);package main
import (
"fmt"
"strings"
)
func longestConsecutive(nums []int) int {
present := make(map[int]struct{}, len(nums))
for _, x := range nums {
present[x] = struct{}{}
}
best := 0
for x := range present { // the set, so each value once
if _, ok := present[x-1]; ok {
continue // not a start: x - 1 will count this run
}
length := 1
for {
if _, ok := present[x+length]; !ok {
break
}
length++ // walk up from the start
}
best = max(best, length)
}
return best
}
func main() {
tests := [][]int{{100, 4, 200, 1, 3, 2}, {0, 3, 7, 2, 5, 8, 4, 6, 0, 1}, {}}
for _, nums := range tests {
fmt.Printf("%s -> %d\n", strings.ReplaceAll(fmt.Sprint(nums), " ", ", "), longestConsecutive(nums))
}
}static int LongestConsecutive(int[] nums)
{
var present = new HashSet<long>(nums.Select(x => (long)x));
int best = 0;
foreach (long x in present) // the set, so each value once
{
if (present.Contains(x - 1)) continue; // not a start: x - 1 will count this run
int length = 1;
while (present.Contains(x + length)) length++; // walk up from the start
best = Math.Max(best, length);
}
return best;
}
int[][] tests = { new[] { 100, 4, 200, 1, 3, 2 }, new[] { 0, 3, 7, 2, 5, 8, 4, 6, 0, 1 }, Array.Empty<int>() };
foreach (var nums in tests)
Console.WriteLine($"[{string.Join(", ", nums)}] -> {LongestConsecutive(nums)}");All six print:
[100, 4, 200, 1, 3, 2] -> 4
[0, 3, 7, 2, 5, 8, 4, 6, 0, 1] -> 9
[] -> 0
- C++, Java and C# store the values as 64-bit numbers so that
x + 1can't overflow whenxis the largest 32-bit integer. Python, JavaScript and Go don't need this. - Every version loops over the set, not over
nums. The edge-case section shows why that matters.
Time and space complexity
It looks like a loop inside a loop, so it's tempting to call it O(n²). Count the work per value instead:
- every value is checked once as a possible start (one
x - 1lookup), and - every value is stepped onto at most once by a walk, because only the run's start walks it.
So the total is about 2n lookups: O(n) time on average. The set holds up to n values: O(n) space.
| Approach | Time | Extra space |
|---|---|---|
| Brute force, searching the array | O(n³) | O(1) |
| Sort, then one walk | O(n log n) | O(1) to O(n) |
| Hash set, walk only from starts | O(n) average | O(n) |
Edge cases and common mistakes
- Empty input: return 0, not 1. Start
bestat 0. - Duplicates:
[1, 2, 2, 3]has a run of length 3. The set drops the extra 2; in the sorted version, equal neighbours must be skipped, not treated as a break. - Looping over
numsinstead of the set: with many copies of a start value, like[1, 1, 1, …, 1, 2, 3, …, 50000], every copy of 1 is a start and walks the whole run again. That's O(n²). Looping over the set visits each value once. - Forgetting the start check: walking up from every value works but is O(n²) on an input like 1, 2, …, n.
- Overflow:
x + 1whenxis 2,147,483,647 overflows a 32-bit int in C++, Java and C#. Use a 64-bit type, or stop at the maximum value. - Negative numbers: nothing special, -3, -2, -1, 0 is a run of 4.
Where it's used in real apps
- Seat maps: finding the longest block of free consecutive seats for a group booking on a flight or a long-distance bus.
- Streaks: a fitness or language app stores the days you were active as a set of day numbers; your longest streak is exactly this problem.
- Spotting gaps in sequence numbers: message queues and databases number their records; the runs between missing numbers show which ranges arrived intact and which need to be fetched again.
- Free time slots: a calendar marks busy 15-minute slots; the longest run of free slot numbers is the longest meeting you can book.
Quick quiz
1. Why only start counting from a number whose
x - 1 is missing?
Such a number is the first value of its run. Starting only there means every run is walked exactly once. Starting from every member would walk the same run again and again, which is O(n²).
2. There's a
while loop inside a for loop. Why is it still O(n)?
The while loop only runs from run starts, and each value belongs to exactly one run, so across the whole program each value is stepped onto at most once. Plus one start check per value: about 2n lookups in total.
3. Why loop over the set rather than the original array?
The array can hold the same start value many times. Each copy would pass the start check and walk the whole run again. The set has each value once.
4. The input is already sorted. Is there anything better than the hash set?
Yes: one pass comparing each value with the previous one gives O(n) time and O(1) extra space, with no set at all.
5. How would you return the run itself, not just its length?
Along with the best length, remember the start value that produced it. The run is start, start + 1, …, start + length - 1.
Solved it yourself and understood the optimal approach? Mark it to track your progress.