Chapter 16 · Hashing

Hash Sets

A hash set is a hash map where you only care about keys — no associated values. It answers one question instantly: “is this element in the collection?” O(1) average for insert, delete, and membership testing. Perfect for deduplication and set-algebra problems.

What is a hash set?

A hash set stores unique values and answers "is this value in the set?" in O(1) on average. It's a hash map with keys but no values. In JavaScript, use Set: new Set(array) removes duplicates, and set.has(x) replaces slow array.includes(x) checks inside loops.

const unique = [...new Set([3, 1, 3, 2, 1])];   // [3, 1, 2]
const seen = new Set();
for (const x of [5, 2, 5]) { if (seen.has(x)) console.log("duplicate", x); seen.add(x); }

const a = new Set([1, 2, 3]), b = new Set([2, 3, 4]);
a.intersection(b);  // Set {2, 3}  (newer browsers)
[...a].filter((x) => b.has(x));   // works everywhere

Hash Map vs Hash Set

HashMap<K, V>

  • Stores key-value pairs
  • get(key) returns the value
  • Example: word -> frequency count
  • Example: id -> user object

HashSet<K>

  • Stores keys only, no values
  • contains(key) returns true/false
  • Example: set of visited URLs
  • Example: set of unique integers

Internally a HashSet is literally a HashMap where each value is a constant placeholder (most implementations use a dummy object or a boolean). The hashing machinery is identical.

Live demo — hash bucket visualiser

A hash set uses the same hashing mechanism as a hash map but stores only keys. Watch keys land in buckets and see how the hash function distributes them.

Hash Map — 8 buckets · h(k) = polyHash(k) % 8

entries: 0
[0]
—
[1]
—
[2]
—
[3]
—
[4]
—
[5]
—
[6]
—
[7]
—

Core operations

hashset.pseudo
1HashSet based on array of buckets:
2 buckets <- array of linked lists, size m
3 size <- 0
4 
5add(key):
6 if contains(key): return // already present, no duplicate
7 idx <- hash(key) mod m
8 buckets[idx].append(key)
9 size <- size + 1
10 if size / m > LOAD_FACTOR_MAX: resize()
11 
12contains(key) -> bool:
13 idx <- hash(key) mod m
14 return key in buckets[idx] // O(1) amortized
15 
16remove(key):
17 idx <- hash(key) mod m
18 buckets[idx].remove(key)
19 size <- size - 1

Set operations

A = {1, 2, 3, 4}   B = {3, 4, 5, 6}

set-operations.pseudo
1union(A, B): // everything in A or B
2 result <- copy of A
3 for each x in B: result.add(x) // add ignores duplicates
4 return result // {1,2,3,4,5,6} — O(|A|+|B|)
5 
6intersection(A, B): // only elements in both
7 result <- new HashSet
8 for each x in A:
9 if B.contains(x): result.add(x)
10 return result // {3,4} — O(min(|A|,|B|))
11 
12difference(A, B): // in A but not in B
13 result <- new HashSet
14 for each x in A:
15 if not B.contains(x): result.add(x)
16 return result // {1,2} — O(|A|)
17 
18isSubset(A, B) -> bool: // every element of A is in B
19 for each x in A:
20 if not B.contains(x): return false
21 return true // O(|A|)

Classic interview patterns

Deduplicate a list

Iterate once, add to set. Set ignores duplicates. Convert back if needed. O(n) time, O(n) space.

Two Sum (find pair summing to target)

For each number x, check if (target - x) is in the set. Insert x into set. Single pass O(n).

Longest consecutive sequence

Put all numbers into a set. For each n, if n-1 is not in set, n starts a sequence. Count forward. O(n) total.

Contains duplicate

Add elements to set one by one. If add returns false (already present), duplicate found. O(n).

Time complexity

add, contains, remove — average case (good hash function)O(1)

Constant time

add, contains, remove — worst case (all keys in same bucket)O(n)

Linear time

union, intersection, difference — proportional to set sizesO(n)

Linear time

space — proportional to number of elements storedO(n)

Linear time

🎯 Quick Check

You need to find all elements that appear in array A but not array B. What is the most efficient approach?

⚠️Hash sets are unordered
A HashSet makes no guarantees about iteration order. If you need sorted output, use a TreeSet (backed by a balanced BST) at O(log n) per operation. If you need insertion-order preservation, use a LinkedHashSet. The performance tradeoff: O(1) (hash) vs O(log n) (tree) vs O(n) (sorted list) per operation.

Hash Sets: summary

Key points

  • Set compares with SameValueZero: objects are unique by reference, not by content.
  • Use a set whenever you only need to check membership or remove duplicates.

Frequently asked questions

›How do I remove duplicates from an array?

[...new Set(array)]. It's O(n) and keeps the first occurrence order.