Hash Sets vs Maps

RoadmapsDSA

Overview

Both Hash Maps (Dictionaries) and Hash Sets are powered by hash tables under the hood. A Hash Map binds a unique key to an associated value (e.g., UserID -> Profile). A Hash Set stores ONLY unique keys, with no associated values.

You use a Map when the data has inherent duality—you need to look up a key to retrieve a specific payload. You use a Set when you purely need to answer a binary existence query: 'Have I seen this exact item before?'

Where used: Sets: Identifying the boundaries of sequences by checking if `num - 1` exists in O(1) time., Maps: Grouping anagrams by mapping a sorted signature string to a list of matching words.

Why learn this

Aha moment

# Deduplicating an array in Python
raw_data = [1, 2, 2, 3, 4, 4, 4, 5]

# The O(n) magic trick:
clean_data = list(set(raw_data))
print(clean_data) # [1, 2, 3, 4, 5]

Prediction: You have to write a loop to filter out duplicates.

Common guess: Deduplication requires sorting the array first or using nested loops.

Because a Set mathematically cannot contain duplicates, simply casting an array to a Set automatically deduplicates it in a single O(n) pass. It is the cleanest, fastest way to extract unique elements in any language.

Common mistakes

Glossary

inherent duality
Having two connected parts, like a paired key and its corresponding value.
semantic data structure
A way of organizing data that clearly communicates the programmer's intent.
binary existence query
A simple yes-or-no question asking whether an item is present or not.

Recall questions

Understanding checks

A developer wants to count how many times each word appears in a book. They try to use a Hash Set, adding each word as they read it. Why does this fail to solve the problem?

Sets enforce strict uniqueness and discard duplicates. At the end, the developer will only have a list of unique words, with no record of their frequencies. They need a Hash Map mapping `Word -> Count`.

This distinction is the crux of choosing between the two structures. Frequencies require a payload (the count), mandating a Map.

You have an array of 100,000 user IDs, and you need to repeatedly check if incoming requests match any of these IDs. Does using a Hash Set or a Hash Map make more sense here?

A Hash Set makes more sense. You only need to verify existence (is the ID in the allowed list?), which requires no associated value.

Sets are the standard data structure for fast O(1) membership testing where no payload is required.

Practice tasks

Array intersection

Given two arrays, `arr1` and `arr2`, return a list of elements that appear in both arrays in O(n + m) time.

Continue learning

Previous: Hash Tables

Return to DSA Roadmap