Data Structures & Algorithms · Module 3 · Lesson 11 min read

Hash Maps & Sets

How hashing works

A hash function turns a key (like "apple") into a number, which picks a bucket in an internal array. So finding a key doesn't require searching; you jump straight to its bucket.

Python's hash structures

StructureStoresExample
dictkey → valueages = {"Ana": 25}
setunique keysseen = {1, 2, 3}
collections.Counterkey → countCounter("banana")
collections.defaultdictkey → value with a defaultdefaultdict(list)

Costs

OperationAverageWorst (many collisions)
Insert, look up, deleteO(1)O(n)

Collisions

Two keys can land in the same bucket. Hash tables handle this (chaining or probing) and resize when they get full, so operations stay O(1) on average.

Rules

  • Keys must be hashable (immutable): str, int, tuple ✅. list and dict ❌.
  • Sets and dicts don't keep duplicates; a set is perfect for "have I seen this?".

💡 When you write a nested loop to find something, ask: "Could a hash map remember it instead?" That's the most common way to go from O(n²) to O(n).

Example

Python
from collections import Counter, defaultdict

# Count words
text = "the cat and the hat and the bat"
counts = Counter(text.split())
print(counts.most_common(2))        # [('the', 3), ('and', 2)]

# Group words by first letter
groups = defaultdict(list)
for word in ["apple", "avocado", "banana", "blueberry", "cherry"]:
    groups[word[0]].append(word)
print(dict(groups))   # {'a': ['apple', 'avocado'], 'b': [...], 'c': ['cherry']}

# First repeated item using a set
def first_repeat(items):
    seen = set()
    for x in items:
        if x in seen:
            return x
        seen.add(x)
    return None

print(first_repeat([3, 8, 1, 8, 3]))   # 8