Browse curriculum

Hash Set

A hash set is a collection of unique elements that uses hashing for O(1) average-time checks, insertions and removals.

0 / 8 · LOAD 0.00

READY

0
1
2
3
4
5
6
7

 

Insert keys and watch where the hash sends them. A collision is two keys landing in one bucket — the two strategies below differ only in what happens next.

 

Key

Collisions

Buckets

8

Intuition

Think of it like a club guest list. You only care IF someone is on the list, not where they are sitting or how many times they appear (duplicates are ignored). When a guest arrives, you check the list instantly using their name (Hash) to see if they are already inside.

Concept

A Hash Set is essentially a Hash Map where the Key is the element itself, and the Value is ignored (or a dummy placeholder).

  • Uniqueness: Stores distinct elements only. Adding a duplicate has no effect.
  • Hashing: Uses the same hashing and collision resolution (Chaining/Probing) as Hash Maps to locate elements.

How it Works

Add(Element):

  1. Compute hash h = hash(element) for bucket index.
  2. Search bucket/probe sequence for the element.
  3. If found, do nothing (already exists).
  4. If not found, insert the element.

Contains(Element):

  1. Compute hash and find index.
  2. Search bucket. If found, return true. Else, false.

Step-by-Step Breakdown

Watch the visualization:

  • Add Unique: Element is hashed and placed in an empty spot or chain.
  • Add Duplicate: System checks, finds it exists, and rejects the addition.
  • Remove: Element is found via hash and deleted.

When to Use

Applications:

  • Removing duplicates from a collection (deduplication).
  • Checking presence/membership (e.g., "Is this IP blocked?").
  • Finding intersection/union of datasets.
  • Visited tracking in Graph algorithms (BFS/DFS).

When NOT to Use

  • Key-Value Pairs: Use Hash Map instead.
  • Ordering: If you need elements sorted or in insertion order, use TreeSet or LinkedHashSet.

How to Identify

"Find unique", "Remove duplicates", "Check if visited", "Common elements".

Applying for software engineering roles? Free, no sign-up:

AI resume checker — match your resume to the job description

Frequently Asked Questions

What is a Hash Set?

A Hash Set is a collection of unique elements that uses a hash table internally to ensure fast O(1) average time membership checks.


Hash Set vs Hash Map?

A Hash Set only stores unique keys, while a Hash Map stores key-value pairs. Many libraries implement Sets using Maps internally.


How does it handle duplicates?

If you try to insert a value already present, the hash function will map to the same bucket where the value is rejected or simply overwritten.