Skip to lesson

Longest consecutive sequence

Given an unsorted integer array nums = [100, 4, 200, 1, 3, 2], the longest consecutive elements sequence is [1, 2, 3, 4] of length 4. Sorting solves this in O(n log n) time, but Longest Consecutive Sequence demands O(n) time—which we achieve with a HashSet and a single one-line guard.

Set lookups

A consecutive run needs no order in the array: 100, 4, 200, 1, 3, 2 contains the run 1, 2, 3, 4, and a repeated value does not lengthen a run.

Example 1 · Finding consecutive pairs of 3 (x - 1, x, x + 1) that sum to a target

SumOfThreeConsecutiveDemo.javaJava
import java.util.Arrays;
public class SumOfThreeConsecutiveDemo {    public static long[] sumOfThree(long num) {        if (num % 3 != 0) {            return new long[0];        }        long mid = num / 3;        return new long[]{mid - 1, mid, mid + 1};    }
    public static void main(String[] args) {        System.out.println("33 -> " + Arrays.toString(sumOfThree(33)));        System.out.println("4  -> " + Arrays.toString(sumOfThree(4)));    }}
Output
33 -> [10, 11, 12]
4  -> []

What this code does

  • Three consecutive integers (x - 1) + x + (x + 1) always sum to 3x.
  • Thus num can be written as the sum of three consecutive integers if and only if num % 3 == 0.

For example, [1, 2, 2, 3] has the consecutive run 1, 2, 3 of length 3.

If we put all elements of nums into a Set<Integer> set = new HashSet<>(), we can check whether curr + 1 exists in the array in O(1) expected time (set.contains(curr + 1)) instead of scanning the array in O(n) time. However, if we start a while (set.contains(curr + 1)) walk from every element in the set, a run like 1, 2, 3, 4 would be walked from 1 (1->2->3->4), again from 2 (2->3->4), again from 3 (3->4), and from 4—taking O(n²) time in the worst case!

  • Putting all elements into a HashSet deduplicates the input and gives O(1) expected membership lookups.
  • Walking curr + 1 from every number without a guard still repeats work and degrades to O(n^2).

Starting only at the start of a run

How do we avoid walking the middle of a run 2 -> 3 -> 4 when we will already walk the full run 1 -> 2 -> 3 -> 4 from 1?

  1. Insert all elements of nums into Set<Integer> set = new HashSet<>().
  2. Loop over each unique integer x in set (not nums, to avoid re-checking duplicates!).
  3. If !set.contains(x - 1), x is the start of a run: set curr = x, len = 1, and while (set.contains(curr + 1)) { curr++; len++; }.
  4. Update best = Math.max(best, len).

Example 2 · Brute force: walk up from every number with a linear search (O(n³) worst case, O(1) space)

LongestConsecutiveBrute.javaJava
public class LongestConsecutiveBrute {    private static boolean contains(int[] nums, int value) {        for (int x : nums) {            if (x == value) {                return true;            }        }        return false;    }
    public static int longestConsecutive(int[] nums) {        int longest = 0;        for (int x : nums) {            int curr = x;            int length = 1;            while (contains(nums, curr + 1)) {                curr++;                length++;            }            longest = Math.max(longest, length);        }        return longest;    }
    public static void main(String[] args) {        int[] a = {100, 4, 200, 1, 3, 2};        System.out.println("[100, 4, 200, 1, 3, 2] -> " + longestConsecutive(a));        int[] b = {0, 3, 7, 2, 5, 8, 4, 6, 0, 1};        System.out.println("[0,3,7,2,5,8,4,6,0,1] -> " + longestConsecutive(b));    }}
Output
[100, 4, 200, 1, 3, 2] -> 4
[0,3,7,2,5,8,4,6,0,1] -> 9

What this code does

  • Every number starts a walk, and every step of a walk searches the whole array for the next number. A long run makes this up to n × n × n steps.
  • The costly part is the search for curr + 1. A sorted array or a hash set can answer it far faster.

Example 3 · Better: sort, then count runs in one scan (O(n log n) time, O(1) extra space)

LongestConsecutiveSort.javaJava
import java.util.Arrays;
public class LongestConsecutiveSort {    public static int longestConsecutive(int[] nums) {        if (nums.length == 0) {            return 0;        }        int[] sorted = nums.clone();        Arrays.sort(sorted);        int longest = 1;        int run = 1;        for (int i = 1; i < sorted.length; i++) {            if (sorted[i] == sorted[i - 1]) {                continue;            }            if (sorted[i] == sorted[i - 1] + 1) {                run++;            } else {                run = 1;            }            longest = Math.max(longest, run);        }        return longest;    }
    public static void main(String[] args) {        int[] a = {100, 4, 200, 1, 3, 2};        System.out.println("[100, 4, 200, 1, 3, 2] -> " + longestConsecutive(a));        int[] b = {0, 3, 7, 2, 5, 8, 4, 6, 0, 1};        System.out.println("[0,3,7,2,5,8,4,6,0,1] -> " + longestConsecutive(b));    }}
Output
[100, 4, 200, 1, 3, 2] -> 4
[0,3,7,2,5,8,4,6,0,1] -> 9

What this code does

  • After sorting, a run of consecutive numbers sits side by side, so one scan can count it. Equal neighbours are skipped.
  • It is faster than brute force because the search for the next number disappears. Sorting still costs O(n log n); a hash set gets to O(n).

Example 4 · Optimal: HashSet, start only at the first number of a run (O(n) time, O(n) space)

LongestConsecutiveDemo.javaJava
import java.util.HashSet;import java.util.Set;
public class LongestConsecutiveDemo {    public static int longestConsecutive(int[] nums) {        Set<Integer> set = new HashSet<>();        for (int x : nums) {            set.add(x);        }        int longest = 0;        for (int x : set) {            if (!set.contains(x - 1)) {                int curr = x;                int length = 1;                while (set.contains(curr + 1)) {                    curr++;                    length++;                }                longest = Math.max(longest, length);            }        }        return longest;    }
    public static void main(String[] args) {        int[] a = {100, 4, 200, 1, 3, 2};        System.out.println("[100, 4, 200, 1, 3, 2] -> " + longestConsecutive(a));        int[] b = {0, 3, 7, 2, 5, 8, 4, 6, 0, 1};        System.out.println("[0,3,7,2,5,8,4,6,0,1] -> " + longestConsecutive(b));    }}
Output
[100, 4, 200, 1, 3, 2] -> 4
[0,3,7,2,5,8,4,6,0,1] -> 9

What this code does

  • In a, only 100, 200, and 1 pass the !set.contains(x - 1) guard; 2, 3, and 4 are skipped in O(1).
  • In b, the duplicate 0 is deduplicated by the HashSet, and the chain 0..8 has length 9.
  • Why it is faster than sorting: set lookups cost O(1), and the x - 1 check means each run is walked exactly once, so there is no sort.

Ask one question before starting a while loop at x: "Is x the very first number of its consecutive run?" x is the start of a run if and only if x - 1 is NOT in the set (!set.contains(x - 1))!

  • For x = 4: 3 is in the set -> skip 4 immediately!
  • For x = 3: 2 is in the set -> skip 3 immediately!
  • For x = 2: 1 is in the set -> skip 2 immediately!
  • For x = 1: 0 is NOT in the set -> 1 is a run start! Walk 1 -> 2 -> 3 -> 4 (length 4).
  • For x = 100: 99 is NOT in the set -> 100 is a run start! Walk 100 (length 1).
Always iterate the outer loop over for (int x : set) rather than for (int x : nums). If nums contains 100,000 copies of the run start 1, looping over nums would run the while loop 100,000 times!

Why it is O(n)

Why is the nested while (set.contains(curr + 1)) loop guaranteed to run in O(n) total time across the entire algorithm?

Example 5 · Counting total HashSet probes to prove O(n) behavior

ConsecutiveProbeCountDemo.javaJava
import java.util.HashSet;import java.util.Set;
public class ConsecutiveProbeCountDemo {    public static void main(String[] args) {        int[] nums = {10, 5, 6, 7, 8, 9, 1, 2, 3, 4};        Set<Integer> set = new HashSet<>();        for (int x : nums) set.add(x);
        int startChecks = 0;        int whileSteps = 0;        int best = 0;        for (int x : set) {            startChecks++;            if (!set.contains(x - 1)) {                int curr = x, len = 1;                while (set.contains(curr + 1)) {                    whileSteps++;                    curr++;                    len++;                }                best = Math.max(best, len);            }        }        System.out.println("n=" + nums.length + ", best=" + best                + ", startChecks=" + startChecks + ", whileSteps=" + whileSteps);    }}
Output
n=10, best=10, startChecks=10, whileSteps=9

What this code does

  • Even when all 10 numbers form one single chain 1..10, the while loop only executes 9 steps in total (when x == 1).
  • For x = 2..10, !set.contains(x - 1) is false, so the while loop executes 0 times.
  • Every number in set is the start of at most 1 chain.
  • Every number in set is stepped onto by curr++ at most once across the entire run.
  • Total HashSet operations <= n (insert) + n (start check) + n (while advances) = 3n = O(n).

Because the guard if (!set.contains(x - 1)) ensures that each maximal consecutive chain [a, a+1, …, b] is traversed at most once—starting only at a. Therefore, any element y ∈ set is visited by the inner while loop (curr + 1) at most once (when walking from the start of y's unique chain).

  • Outer loop over set: at most n checks of !set.contains(x - 1).
  • Inner while loop across the entire run: at most n successful set.contains(curr + 1) steps.

Total HashSet lookups ≤ 3n = O(n) expected time, and O(n) space.

Next step

Check your understanding

10 quick questions