Hashing & Sets
Hash Map Counting
🗃️
Picture this
A clerk opens labeled drawers instantly, adding one tally mark for every matching key.
When you see it
Signal words
If the prompt uses any of these, this pattern should come to mind first.
frequencycountanagramtwo sumseen beforelookup
Ask yourself
- Do you need to remember whether a value appeared before?
- Are counts, frequencies, or complements central to the answer?
- Can one pass with a
Mapreplace a nested scan?
Canonical template
const count = new Map<number, number>();
for (const x of nums) {
count.set(x, (count.get(x) ?? 0) + 1);
}
for (const x of nums) {
const need = target - x;
if ((count.get(need) ?? 0) > 0) return true;
}
return false;
Common pitfalls
Forgetting that
0is a valid stored count or index.
Using an object when keys may not be safe property names.