Sets & Maps — Built-in & Custom

0/14 in this phase0/57 across the roadmap

📖 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 sets
  • delete(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

codeTap to expand ⛶
1// SET — Unique values, O(1) lookup
2const 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]
8
9// Remove duplicates from array — one-liner!
10const unique = [...new Set([1, 2, 2, 3, 3, 3])]; // [1, 2, 3]
11
12// SET OPERATIONS
13function 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}
22
23// MAP — Key-value, any key type
24const map = new Map<string, number>();
25map.set("alice", 30);
26map.set("bob", 25);
27console.log(map.get("alice")); // 30
28console.log(map.has("charlie")); // false
29
30// Frequency counter with Map
31function 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}
38
39// WEAKMAP & WEAKSET — Keys can be garbage collected
40const 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 it
44
45// Check if array has duplicates — O(n) with Set
46function hasDuplicates<T>(arr: T[]): boolean {
47 return new Set(arr).size !== arr.length;
48}
49
50// Find common elements between two arrays
51function 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:

  1. Remove duplicates from an array using a Set
  2. Find the intersection of two arrays
  3. Find the union of two arrays (no duplicates)
  4. Implement Set operations: union, intersection, difference
  5. Check if one array is a subset of another
  6. Count unique elements in an array
  7. Find the first duplicate in an array using a Set
  8. Group elements by frequency using a Map
  9. Find all pairs with a given sum using a Set
  10. 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