Data Structures & Algorithms / Module 2: Hashing
Topic 2.4
Hash sets
A hash map without values, for answering 'seen it before?' in one step.
Watch: each number is checked just once: "seen it before?" The answer is instant, without rereading the list.
- being checked
- finished / the result
- no longer used
Like a guest list with a stamp
At an event's door, every guest gets a stamp on their hand. When someone wants back in, the staff just check for the stamp; they don't reread the whole guest list. A Set works like that. In the figure, each number is checked in the Set in one step, then added. As soon as a number is already stamped, we know it is the first repeat.
Patterns you will use often
Code, for programmersRemoving duplicates
const unique = [...new Set([3, 1, 3, 2, 1])]; // [3, 1, 2]Code, for programmersThe first repeated number
function firstRepeat(list) {
const seen = new Set();
for (const x of list) {
if (seen.has(x)) return x; // one step
seen.add(x); // one step
}
return null;
}Code, for programmersDo any two numbers add up to target?
function hasPair(list, target) {
const seen = new Set();
for (const x of list) {
if (seen.has(target - x)) return true; // its partner came earlier
seen.add(x);
}
return false;
}All three are O(n): each element is seen once, and each check is one step. Without a Set they are usually written with a loop inside a loop, O(n²).
Quiz
What does a hash set store?
Finding the first repeated number among 1 million numbers with a Set takes…
To count how often each word appears, the right structure is…
0 of 3 answered.