Find the length of the longest consecutive sequence in an unsorted array. Compare sorting, HashSet and streams.
Problem
[100, 4, 200, 1, 3, 2] → 4 (the run 1, 2, 3, 4). Required: O(n). Frequently asked at product companies.
Pattern
HashSet for O(1) membership + "only start counting at the beginning of a run" so each element is visited a constant number of times.
Approach 1: Check runs from every element (feasible, O(n²) or worse)
class ConsecutiveBrute {
static boolean contains(int[] a, int x) { for (int v : a) if (v == x) return true; return false; }
static int longest(int[] nums) {
int best = 0;
for (int x : nums) {
int len = 1;
while (contains(nums, x + len)) len++; // linear search for each step
best = Math.max(best, len);
}
return best;
}
}Approach 2: Sort and scan (O(n log n))
Skip duplicates; reset the run when there is a gap.
import java.util.Arrays;
class ConsecutiveSort {
static int longest(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 = a[i] == a[i - 1] + 1 ? run + 1 : 1;
best = Math.max(best, run);
}
return best;
}
}Approach 3: HashSet, start only at run beginnings (O(n)) — optimal
A number starts a run only if x - 1 is absent; from there count upwards. Every number is visited at most twice overall.
import java.util.HashSet;
import java.util.Set;
class ConsecutiveHashSet {
static int longest(int[] nums) {
Set<Integer> set = new HashSet<>();
for (int x : nums) set.add(x);
int best = 0;
for (int x : set) {
if (set.contains(x - 1)) continue; // not the start of a run
int len = 1;
while (set.contains(x + len)) len++;
best = Math.max(best, len);
}
return best;
}
}Approach 4: Java 8 streams version of the same idea
import java.util.Arrays;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
class ConsecutiveStreams {
static int longest(int[] nums) {
Set<Integer> set = Arrays.stream(nums).boxed().collect(Collectors.toSet());
return set.stream()
.filter(x -> !set.contains(x - 1))
.mapToInt(x -> (int) IntStream.iterate(x, v -> set.contains(v), v -> v + 1).count()) // Java 9 iterate
.max().orElse(0);
}
}
class ConsecutiveDemo {
public static void main(String[] args) {
int[] nums = {100, 4, 200, 1, 3, 2, 2};
System.out.println(ConsecutiveBrute.longest(nums) + " " + ConsecutiveSort.longest(nums) + " "
+ ConsecutiveHashSet.longest(nums) + " " + ConsecutiveStreams.longest(nums)); // 4 4 4 4
}
}Feasible → optimal
Brute force O(n²)–O(n³); sorting O(n log n) with O(1) extra if sorting in place; HashSet O(n) time and O(n) space is the expected answer; streams express the same O(n) algorithm with boxing overhead.
Follow-up questions interviewers ask
Try answering each one before you open it.
Related (same pattern): does any pair sum to a target / contains duplicate within k indices?
Both use a HashSet (or HashMap of value → last index) for O(1) lookups while scanning once. "Contains duplicate within distance k": keep a sliding HashSet of the last k elements, removing nums[i - k - 1] as you go: O(n) time, O(k) space.
Related (same pattern): count distinct islands of numbers or merge overlapping ranges given unsorted points.
If you need the runs themselves (not just the length), use the same "start of run" trick and collect [x, x + len - 1] ranges; to keep ranges up to date under insertions, a TreeMap<start, end> with floorEntry/ceilingEntry merges neighbours in O(log n) per insert ("summary ranges" / "data stream as disjoint intervals").