Java Array Program · A37
Longest Consecutive Sequence in Java
Put every value in a set. Only start counting at numbers whose predecessor is missing; from there, count upwards while the next number exists.
Problem Statement
Given an unsorted array of integers, return the length of the longest sequence of consecutive integers that all appear in the array, in any order.
Duplicates count once. An empty array returns 0.
Input/Output Examples
[10, 5, 12, 3, 11, 4, 6]Output4Explanation: 3, 4, 5, 6 is longer than 10, 11, 12.[]Output0Explanation: no values.[1, 2, 0, 1]Output3Explanation: 0, 1, 2; the second 1 adds nothing.Visual Explanation
- Setvalues3456101112duplicates removed
- Start at 3run34562 is missing, so 3 starts a run length 4
- Start at 10run1011129 is missing length 3
- Skip others4, 5, 6, 11, 12 have a predecessor
- Done4
Skipping numbers that have a predecessor is what keeps the algorithm linear: each run is walked only from its first element, so every value is visited a constant number of times.
Approaches
The set approach meets the O(n) requirement. Sorting is simpler but takes O(n log n).
Approach 1: HashSet With Run Starts (Recommended)
Idea: add all values to a set; for each value with no predecessor, count how far the run continues.
- Put every value in a
HashSet. - For each value
vin the set, skip it ifv - 1is present. - Otherwise count
v + 1,v + 2, … while they exist. - Keep the longest count.
Time: O(n) · Space: O(n).
Approach 2: Sort, Then Scan
Idea: sort a copy; count runs where each value is exactly one more than the previous, ignoring repeats.
- Sort a copy of the array.
- Skip equal neighbours.
- Extend the run when the difference is 1; otherwise restart it.
Time: O(n log n) · Space: O(n).
Java Solutions
Each tab is a complete program that runs on Java 17 or later. Both programs print the same output for the same inputs.
Approach 1: HashSet With Run Starts (Recommended)
Looping over the set instead of the array avoids repeated work for duplicate values.
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
public class ConsecutiveSet {
// Only start counting at numbers that begin a run (x - 1 is absent)
static int longestConsecutive(int[] arr) {
Set<Integer> set = new HashSet<>();
for (int v : arr) {
set.add(v);
}
int best = 0;
for (int v : set) {
if (!set.contains(v - 1)) {
int length = 1;
while (set.contains(v + length)) {
length++;
}
best = Math.max(best, length);
}
}
return best;
}
public static void main(String[] args) {
int[][] inputs = {{10, 5, 12, 3, 11, 4, 6}, {}, {1, 2, 0, 1}};
for (int[] arr : inputs) {
System.out.println(Arrays.toString(arr) + " -> " + longestConsecutive(arr));
}
}
}
[10, 5, 12, 3, 11, 4, 6] -> 4 [] -> 0 [1, 2, 0, 1] -> 3
Time complexity: O(n) · Space complexity: O(n).
Approach 2: Sort, Then Scan
Easy to get right, and a good fallback if hashing is not allowed.
import java.util.Arrays;
public class ConsecutiveSort {
// Sort a copy, then count runs where each value is one more than the previous (repeats are skipped)
static int longestConsecutive(int[] arr) {
if (arr.length == 0) {
return 0;
}
int[] s = arr.clone();
Arrays.sort(s);
int best = 1;
int run = 1;
for (int i = 1; i < s.length; i++) {
if (s[i] == s[i - 1]) {
continue;
}
run = (s[i] == s[i - 1] + 1) ? run + 1 : 1;
best = Math.max(best, run);
}
return best;
}
public static void main(String[] args) {
int[][] inputs = {{10, 5, 12, 3, 11, 4, 6}, {}, {1, 2, 0, 1}};
for (int[] arr : inputs) {
System.out.println(Arrays.toString(arr) + " -> " + longestConsecutive(arr));
}
}
}
[10, 5, 12, 3, 11, 4, 6] -> 4 [] -> 0 [1, 2, 0, 1] -> 3
Time complexity: O(n log n) · Space complexity: O(n).
Complexity Analysis
| Approach | Time Complexity | Space Complexity |
|---|---|---|
| HashSet With Run Starts | O(n) | O(n) |
| Sort, Then Scan | O(n log n) | O(n) |
Here n is the number of elements. The set approach visits each value a constant number of times; sorting dominates the second approach.
Interview Tips and Recommended Approach
- Only count from run starts. Counting from every value makes the algorithm quadratic.
- Handle duplicates. They must not break or extend a run.
- Iterate over the set. Iterating over the original array repeats work for duplicates.
- Mention union-find as another way to merge neighbouring values.
Recommended Approach: HashSet With Run Starts
Why: it meets the linear-time requirement with a single set and a simple "is this a start?" check.