Longest Consecutive Sequence
Find the longest run of consecutive numbers in an unsorted array in linear time, with a set.
You are given an array of integers nums
The solution must run in O(n) time, where n is the length of the array: the number of steps may grow only in proportion to n.
Example 1
Output: 4
Explanation: the longest run is 1, 2, 3, 4.
Example 2
Output: 9
Explanation: the longest run is 0 to 8.
The Idea
Picture six number cards dealt on a table in no order: 100, 4, 200, 1, 3 and 2. Pick them up and lay them out by value, and 1, 2, 3 and 4 line up with no gap between them, while 100 and 200 stand alone. That run of four is the longest, so the answer is 4.
Laying the cards out by value is sorting, and sorting n numbers takes about n log n steps, more than the n steps the problem allows. So can we find the runs without putting the numbers in order?
What do we really need to know about a number? Only whether its neighbours are there. Is 2 in the array? Is 5? Keep the numbers in a set, a collection that answers "is this value in it?" in one step, and each question is cheap. From 1 we can walk up: 2 is there, 3 is there, 4 is there, and 5 is not, so the run from 1 has length 4.
But where should a walk begin? Walking up from every number would measure the run 1, 2, 3, 4 again from 2, from 3 and from 4. Only one number in a run has no value just below it in the set: its smallest number. Look at the picture below.
0 is not in the set, so 1 starts a run, and the walk goes up through 2, 3 and 4 until it reaches the missing 5: length 4. 2, 3 and 4 each have a value just below them, so no walk starts there. 99 and 199 are missing too, so 100 and 200 each start a run of length 1.
So the key is to walk up only from the start of a run. Each run is then walked once, and every number is looked at only a couple of times, however long its run is.
Solution Approach
Turning that idea into code means settling three things: where the numbers are kept, where a walk starts, and what happens to repeated values.
Where the numbers are kept
Which structure answers "is x + 1 there?" quickly? Searching the array itself takes up to n steps for every question. Java's HashSetHashSet<Integer>
Sorting would also give the right answer: after Arrays.sort(nums)
Where a walk starts
How does the code know that a number starts a run? A number xx - 1x + 1x + 2
Is the check worth it? Without it the answer stays the same, but the work grows quickly. Take the numbers 1 to 10,000, one long run. Walking up from every number makes 50,005,000 lookups in the set. With the check there are 20,000: one check of x - 1
Repeated values
What if a number appears twice, as 0 does in Example 2? The set keeps one copy of it. The code loops over the set, not the array, so the second 0 is never checked or walked from again, and it cannot make a run longer.
Java Solution
The method longestConsecutive
- First, add every number of
to anums calledHashSet , so a repeated number keeps one copy.set - Set
, the longest run found so far, to 0. Then loop overbest , taking each number asset .x - For each
, checkx . If the number below is there,set.contains(x - 1) is inside a run that starts lower, so skip it.x - Otherwise
starts a run. Setx to 1, and whilelength is true, add 1 toset.contains(x + length) .length - Keep the larger of
andbest inlength . When the loop is done, returnbest .best
The main
import java.util.HashSet;
import java.util.Set;
public class LongestConsecutiveSequence {
public static int longestConsecutive(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; // x is not the start of a run
}
int length = 1;
while (set.contains(x + length)) {
length++; // walk up the run x, x+1, x+2, ...
}
best = Math.max(best, length);
}
return best;
}
public static void main(String[] args) {
System.out.println(longestConsecutive(new int[] {100, 4, 200, 1, 3, 2}));
System.out.println(longestConsecutive(new int[] {0, 3, 7, 2, 5, 8, 4, 6, 0, 1}));
System.out.println(longestConsecutive(new int[] {1, 2, 2, 3}));
System.out.println(longestConsecutive(new int[] {-1, 0, 1, 10}));
System.out.println(longestConsecutive(new int[] {5}));
System.out.println(longestConsecutive(new int[] {}));
}
}
Running it prints:
4
9
3
3
1
0
The first two lines, 49[1, 2, 2, 3]
The fourth line comes from [-1, 0, 1, 10]best
The original implementation,
Complexity
The work is filling the set, plus one check for each number and one walk for each run.
- Time: O(n) on average, where n is the length of the array. Adding the n numbers to the set takes n steps. The loop makes one
check per number, and since walks start only at run starts, all the walks together visit each number once. Set lookups take one step on average, not in every case, which is why the bound is an average.contains(x - 1) - Space: O(n) for the set, which stores each different number once. Besides it, the loop keeps only
andbest .length
Another way joins each number with the number one above it into groups, using a structure called Union-Find, and then measures the largest group. Union-Find is used in