← All patterns
25 / 29
Hashing & Sets

Set Membership

🧿
Picture this

A gate guard checks each token against a short forbidden list and waves through only unseen visitors.

When you see it

Signal words

If the prompt uses any of these, this pattern should come to mind first.

uniqueduplicatecontainsvisitedmembershipintersection
Watch it run

Ask yourself

  1. Is the question only about presence, not count?
  2. Do you need uniqueness, intersection, or visited state?
  3. Can membership checks be O(1)?

Canonical template

const seen = new Set<string>();
for (const item of items) {
  if (seen.has(item)) return true;
  seen.add(item);
}
return false;

Common pitfalls

Storing mutable objects when value equality is expected.

Waiting too long to mark visited in graph-style problems.