← Index

Hash-Based Structures

HashSet

A HashMap that only remembers keys — 'have I seen this?' in O(1).

What it is

A set stores unique values with the same O(1) average lookup as a hash map, minus the value half — it only answers membership questions. In JS, this is the built-in Set, and it's one of the most underused tools for turning an O(n²) 'check every pair' loop into O(n).

Real-world examples

Where you've probably used this already

Complexity

Add / Has / Delete O(1) average
Space O(n)

Code

// HashSet — like a HashMap but only cares about keys (no values).
// Answers one question fast, O(1) average: "have I seen this before?"
// In JS you almost always just use the built-in Set.

const seen = new Set();
seen.add("apple");
seen.add("banana");
seen.add("apple"); // duplicate, ignored — a Set only stores unique values

console.log("Set contents:", seen); // Set { 'apple', 'banana' }
console.log("has('apple'):", seen.has("apple")); // true
console.log("size:", seen.size); // 2

// --- Example: dedupe an array in one line ---
const nums = [1, 2, 2, 3, 3, 3, 4];
const unique = [...new Set(nums)];
console.log("unique:", unique); // [1,2,3,4]

// --- Example: detect a duplicate, O(n) instead of O(n^2) ---
function hasDuplicate(arr) {
  const seenValues = new Set();
  for (const val of arr) {
    if (seenValues.has(val)) return true;
    seenValues.add(val);
  }
  return false;
}
console.log("hasDuplicate([1,2,3,2]):", hasDuplicate([1, 2, 3, 2])); // true

// --- Example: find the intersection of two arrays ---
function intersection(a, b) {
  const setA = new Set(a);
  return b.filter((item) => setA.has(item));
}
console.log(
  "intersection([1,2,3],[2,3,4]):",
  intersection([1, 2, 3], [2, 3, 4]),
); // [2,3]

// Under the hood a Set is really just a HashMap that discards the value
// and only keeps the key — same hashing, same O(1) average lookup.