Sets & Maps — Built-in & Custom
📖 Concept
Set stores unique values — no duplicates allowed. Map stores key-value pairs with any key type. Both are critical for O(1) lookups in interviews.
JavaScript Set:
add(value)— O(1)has(value)— O(1) — THE reason to use setsdelete(value)— O(1)size— number of unique elements- Iterable — supports for...of, spread, forEach
JavaScript Map:
set(key, value)— O(1)get(key)— O(1)has(key)— O(1)delete(key)— O(1)- Any key type (objects, functions, primitives)
- Preserves insertion order
Set operations:
- Union: A ∪ B = all elements in either
- Intersection: A ∩ B = elements in both
- Difference: A − B = elements only in A
- Symmetric Difference: elements in one but not both
When to use:
- Need to check existence fast → Set
- Need to count occurrences → Map
- Need to remove duplicates → Set
- Need key-value association → Map
🏠 Real-world analogy: A Set is like a guest list — each name appears once. A Map is like a phone book — each name maps to a phone number.
💻 Code Example
1// SET — Unique values, O(1) lookup2const set = new Set([1, 2, 3, 2, 1]);3console.log(set); // Set { 1, 2, 3 }4console.log(set.has(2)); // true — O(1)!5set.add(4);6set.delete(1);7console.log([...set]); // [2, 3, 4]89// Remove duplicates from array — one-liner!10const unique = [...new Set([1, 2, 2, 3, 3, 3])]; // [1, 2, 3]1112// SET OPERATIONS13function union<T>(a: Set<T>, b: Set<T>): Set<T> {14 return new Set([...a, ...b]);15}16function intersection<T>(a: Set<T>, b: Set<T>): Set<T> {17 return new Set([...a].filter(x => b.has(x)));18}19function difference<T>(a: Set<T>, b: Set<T>): Set<T> {20 return new Set([...a].filter(x => !b.has(x)));21}2223// MAP — Key-value, any key type24const map = new Map<string, number>();25map.set("alice", 30);26map.set("bob", 25);27console.log(map.get("alice")); // 3028console.log(map.has("charlie")); // false2930// Frequency counter with Map31function frequency(arr: number[]): Map<number, number> {32 const freq = new Map<number, number>();33 for (const n of arr) {34 freq.set(n, (freq.get(n) || 0) + 1);35 }36 return freq;37}3839// WEAKMAP & WEAKSET — Keys can be garbage collected40const weakMap = new WeakMap<object, string>();41let obj = { id: 1 };42weakMap.set(obj, "data");43obj = null; // Object can now be GC'd — WeakMap won't prevent it4445// Check if array has duplicates — O(n) with Set46function hasDuplicates<T>(arr: T[]): boolean {47 return new Set(arr).size !== arr.length;48}4950// Find common elements between two arrays51function commonElements(a: number[], b: number[]): number[] {52 const setA = new Set(a);53 return b.filter(x => setA.has(x));54}
🏋️ Practice Exercise
Practice Problems:
- Remove duplicates from an array using a Set
- Find the intersection of two arrays
- Find the union of two arrays (no duplicates)
- Implement Set operations: union, intersection, difference
- Check if one array is a subset of another
- Count unique elements in an array
- Find the first duplicate in an array using a Set
- Group elements by frequency using a Map
- Find all pairs with a given sum using a Set
- Implement a simple cache using Map with TTL (time-to-live)
⚠️ Common Mistakes
Using Object instead of Map for non-string keys — Object keys are always strings
Forgetting that Set uses === for comparison — objects are compared by reference, not value
Not knowing WeakMap/WeakSet — use them for caching to avoid memory leaks
Assuming Set preserves insertion order for numbers — it does in JS, but don't rely on this in algorithms
Using Array.includes() for repeated lookups — O(n) per check; convert to Set for O(1)
💼 Interview Questions
🎤 Mock Interview
Practice a live interview for Sets & Maps — Built-in & Custom