Core Module
12 min forge

Sets & Uniqueness

Learn how to efficiently handle unique collections and perform set operations like intersection and union.

πŸ›Έ Sets: The Uniqueness Guard

A Set is a collection of values where each value must be unique. Internally, most sets use a hash table to ensure that checking for the existence of an item takes constant time.

πŸ’‘ The Logic (ELI5)

Think of a Set as a Guest List for a private party:

  1. When someone arrives, you check if their name is on the list.
  2. If they are already there, you don't let a second "Duplicate" of them in.
  3. You can quickly tell if someone is at the party without looking at everyone inside.

πŸ” The Deep Dive

Core Properties

  • No Duplicates: Automatically handles redundant data.
  • O(1) Operations: Adding, Removing, and Checking (has) are all constant time.
  • Set Operations: Support for Mathematical operations like Union, Intersection, and Difference.

Set vs. Array

  • Array: Keeps items in order, allowed to have duplicates, searching takes $O(n)$ time.
  • Set: Doesn't guarantee order (usually), strictly unique, searching takes $O(1)$ time.

πŸ› οΈ Code Forge: Set Operations

javascript Standard
/** * Using the native JavaScript Set object */ const guestList = new Set(['Alice', 'Bob']); // 1. Adding (O(1)) guestList.add('Charlie'); guestList.add('Alice'); // Does nothing, Alice is already there // 2. Checking Existence (O(1)) if (guestList.has('Alice')) { console.log("Alice is here!"); } // 3. Removing guestList.delete('Bob'); // 4. Converting back to Array (Useful for removing duplicates) const uniqueItems = [...guestList]; /** * Finding Intersection of two arrays */ function intersection(arr1, arr2) { const set1 = new Set(arr1); // Filter arr2 for items that exist in set1 return arr2.filter(item => set1.has(item)); }

🎯 Interview Pulse

Use Cases

  • Removing Duplicates: The fastest way to deduplicate an array is [...new Set(arr)].
  • Existential Questions: "Have we seen this number before?" $\rightarrow$ Use a Set.
  • Cycle Detection: Storing visited nodes in a graph or linked list.

Common Questions

  • Intersection of Two Arrays: Use a set for the smaller array.
  • Happy Number: Use a set to detect if you've entered a loop of numbers.
  • Contains Duplicate: Check if set.size !== array.length.
  • Longest Consecutive Sequence: A high-tier problem solved using a Set in $O(n)$.