The hash set pattern: how to spot it
Updated
A hash set answers one question fast: have I seen this before? Use it when you only care whether a value exists, not how often or where. It turns membership checks from a scan into constant time.
When to reach for it
- The problem asks about duplicates, uniqueness, or values two collections share.
- You need to know whether a value exists, and nothing else about it.
- A brute-force answer scans a list inside a loop just to check membership.
The usual shape
seen = set()
for x in items:
if x in seen:
return True # duplicate found
seen.add(x)
return False3 LeetCode hash sets problems, easiest first
- Contains Duplicate easy
Insert as you scan. A failed insert, or a contains-hit, is the duplicate.
- Intersection of Two Arrays easy
Put the smaller collection in a set, then probe it with the other.
- Happy Number easy
The sum-of-squares walk is a chain. A seen-set catches the cycle.
check which skills you have 10 minutes, free, no account.