CMD Guide
HomeDSAHashing

Introduction to HashSets

A HashSet stores each element by computing its hash code, mapping that hash to one of a fixed number of buckets (index = hash mod capacity), and short-circuiting insert/lookup/delete to that single bucket instead of scanning the whole collection — uniqueness and O(1) average operations are both side effects of this addressing scheme, not separate features bolted on.

Recognize the pattern

Brute force vs. optimal

Brute force: keep elements in an array/list; to check membership or insert-if-absent, linearly scan every existing element. Insert-if-absent costs O(n) per call because you must scan before you know it's new; n insertions cost O(n²) total.

Optimal (HashSet): compute hash(x), jump directly to bucket hash(x) % capacity, and compare only against the few elements colliding in that bucket. Insert-if-absent becomes O(1) average; n insertions cost O(n) total.

Complexity, derived

Let n = number of elements, m = number of buckets (capacity). The load factor α = n/m. Java's HashSet (backed by HashMap) resizes (doubles m) whenever α would exceed 0.75, keeping α bounded.

Assume a good hash function distributes keys uniformly. Expected chain length in any bucket = α, a constant once α is bounded (≤0.75). So:

Traced example — dedup a stream

Insert [7, 3, 7, 5, 3] into a HashSet with capacity m = 4 (indices 0-3), hash = value % 4:

Inserthash % 4Bucket contents afterResult
73bucket3: [7]added
33bucket3: [7,3]added (collision, chained)
73bucket3: [7,3]rejected — 7 already in chain
51bucket1: [5]added
33bucket3: [7,3]rejected — 3 already in chain

Final set: {7, 3, 5} — order not guaranteed to match insertion order.

Reference implementation

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class DedupExample {
    public static List<Integer> firstOccurrences(int[] nums) {
        Set<Integer> seen = new HashSet<>();
        List<Integer> result = new ArrayList<>();
        for (int n : nums) {
            if (seen.add(n)) {
                // add() returns true only the first time n is seen
                result.add(n); // keep first occurrences, in input order
            }
        }
        return result;
    }
}

Pitfalls

When to use / when not — trade-offs

NeedStructureWhy
Fast membership check, no ordering, no valuesHashSetO(1) avg add/contains/remove
Key→value associationHashMapHashSet is literally backed by HashMap with a dummy value
Need sorted iteration / range queriesTreeSetO(log n) ops via balanced BST, but gives ordering HashSet can't
Need insertion-order iterationLinkedHashSetslightly more memory (extra linked list), same O(1) avg ops
Elements are small dense integers, memory-criticalBitSetO(1) ops with far less memory, but only for integer domains
One-shot sorted, unique output from a batchsort + unique passO(n log n) but low constants, no hash worst case, and the result comes out ordered

Takeaways

Recall: Why does resizing a HashSet (doubling capacity and rehashing all elements) still keep amortized insertion at O(1), even though a single resize costs O(n)?


Synthesized from standard HashSet/HashMap internals (Java Collections Framework docs and algorithm literature on hashing with chaining) and the original page's HashSet vs. HashTable framing.

🤖 Don't fully get this? Learn it with Claude

Stuck on Introduction to HashSets? Open Claude, copy a block below, and it'll teach you this exact concept — visually and interactively.

🎨 Explain it visually

Build the mental picture, not memorization.

I just read a lesson on **Introduction to HashSets** (DSA) and want to truly understand it. Explain Introduction to HashSets from first principles using ONE vivid real-world analogy and a visual mental model — draw it as ASCII art or a clear step-by-step diagram — with a concrete example using real numbers. Then ask me one question to check I got the mental picture, and wait for my reply. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
🤔 Walk me through it (interactive)

Socratic — adapts to where you're stuck.

Teach me **Introduction to HashSets** interactively. Ask me ONE guiding question at a time, wait for my answer, and adapt to my confusion — build the idea with me step by step instead of explaining it all at once. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
🧪 Quiz me & fix my gaps

Active recall exposes what you missed.

Quiz me on **Introduction to HashSets** with 5 questions, easy to tricky, ONE at a time. Tell me if each answer is right; at the end, explain clearly what I got wrong and why. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
🧠 Make it stick

Intuition + hook + flashcards for long-term memory.

Help me remember **Introduction to HashSets** for the long term: give the one-sentence intuition, a memorable hook/mnemonic, a tiny worked example, and 3 active-recall flashcards (Q -> A). If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.

📝 My notes