Arrays & Hashing · Pattern 18 of 26

Hash set lookups

Put everything in a set, then ask O(1) questions. For runs of consecutive numbers, start counting only at numbers whose predecessor is missing, so the whole thing is O(n).

3 variations · 6 problems · 2 with animated walkthroughs

Watch the lesson

Concepts first, then the problem and every approach, step by step.

Space to play or pause · ← → to jump a step · click or drag the bar to seek

When to use it

  • Longest run of consecutive values in an unsorted array, in O(n)
  • Have I seen this value (or its partner) before?

The template

Hash Set Lookup
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;       // not the start of a run
        int len = 1;
        while (set.contains(x + len)) len++;
        best = Math.max(best, len);
    }
    return best;
}

The variations

  1. 1Start only at the beginning of a run

    A number begins a run if x − 1 is missing. Count up from there. The same idea finds the longest gap run in bar positions.

  2. 2Seen it before?

    One set and one pass. For a fair swap, compute the difference you need and look for the partner in the other set.

    Now you solve
  3. 3More practice

    More problems that use this pattern. Try them once the variations above feel easy.

Mistakes to avoid

  • Counting from every number instead of only run starts: that is O(n²) on [1..n].
  • Iterating over the original array with duplicates instead of the set.
Next: Simulation: do exactly what the problem says →

Mark it done once you can write the template from memory and you have solved the worked examples yourself.