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, in no particular order. Consecutive integers follow each other with no gap, such as 4, 5, 6 and 7. Return the length of the longest run of consecutive integers that can be made from the values in the array, taken in any order. A value that appears more than once counts once.

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
Input: nums = [100, 4, 200, 1, 3, 2]
Output: 4
Explanation: the longest run is 1, 2, 3, 4.
Example 2
Input: nums = [0, 3, 7, 2, 5, 8, 4, 6, 0, 1]
Output: 9
Explanation: the longest run is 0 to 8.
Solution

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.

The values 1, 2, 3, 4, 100 and 200 laid out by value. 0 is missing, so 1 starts a run; the walk goes up through 2, 3 and 4 and stops at the missing 5, for a length of 4. 100 and 200 each start a run of length 1.

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 HashSet finds a value from its hash code, a number computed from the value, so it answers in one step on average. So all the numbers first go into a HashSet<Integer>.

Sorting would also give the right answer: after Arrays.sort(nums), the runs sit side by side and one pass measures them. But the sort alone takes O(n log n) time, which is more than the problem allows.

Where a walk starts

How does the code know that a number starts a run? A number x starts a run when x - 1 is not in the set. Only then does the walk begin: it checks x + 1, x + 2 and so on, counting as it goes, and stops at the first missing value.

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 per number, plus a single walk of 10,000 lookups from 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 works in these steps:

  1. First, add every number of nums to a HashSet called set, so a repeated number keeps one copy.
  2. Set best, the longest run found so far, to 0. Then loop over set, taking each number as x.
  3. For each x, check set.contains(x - 1). If the number below is there, x is inside a run that starts lower, so skip it.
  4. Otherwise x starts a run. Set length to 1, and while set.contains(x + length) is true, add 1 to length.
  5. Keep the larger of best and length in best. When the loop is done, return best.

The main method runs both examples, an array with a repeated value, a mix of negative and positive numbers, a single number and an empty array.

Java
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:

Output
4
9
3
3
1
0

The first two lines, 4 and 9, answer the two examples. In the second, 0 appears twice, yet the run 0 to 8 counts nine numbers, each once. The third line comes from [1, 2, 2, 3]: the run is 1, 2, 3, and the repeated 2 adds nothing to it.

The fourth line comes from [-1, 0, 1, 10]. Negative numbers follow the same rule: -2 is missing, so -1 starts the run -1, 0, 1, and 10 stands alone. The last two lines are the smallest inputs. One number is a run of length 1, and an empty array has no run at all, so best stays 0.

The original implementation, LongestConsecutiveSequence.java, is on GitHub.

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 contains(x - 1) 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.
  • Space: O(n) for the set, which stores each different number once. Besides it, the loop keeps only best and 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 Number of Connected Components, but for this problem the set is simpler.