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).
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
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;
} def longest_consecutive(nums):
s = set(nums)
best = 0
for x in s:
if x - 1 in s:
continue # not the start of a run
length = 1
while x + length in s:
length += 1
best = max(best, length)
return best int longestConsecutive(vector<int>& nums) {
unordered_set<int> s(nums.begin(), nums.end());
int best = 0;
for (int x : s) {
if (s.count(x - 1)) continue; // not the start of a run
int len = 1;
while (s.count(x + len)) len++;
best = max(best, len);
}
return best;
} function longestConsecutive(nums) {
const s = new Set(nums);
let best = 0;
for (const x of s) {
if (s.has(x - 1)) continue; // not the start of a run
let len = 1;
while (s.has(x + len)) len++;
best = Math.max(best, len);
}
return best;
} The variations
-
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.
Now you solve -
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 -
3More practice
More problems that use this pattern. Try them once the variations above feel easy.
Problems
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.
Mark it done once you can write the template from memory and you have solved the worked examples yourself.