Data structures

Hash maps, visualized.

Turn the key into a number, and the number tells you which box to open. No searching. Watch keys land in buckets, collide and move when the map grows, then solve Two Sum with one.

What is a hash map?

A hash map stores key → value pairs, like a name and a phone number. It keeps an array of slots called buckets. To store a pair it runs the key through a hash function, which turns the key into a number, then takes the remainder by the number of buckets. That remainder is the bucket the pair lives in.

To find a key later, it does the same sum and jumps straight to that bucket, instead of looking through every pair. So put, get and delete cost O(1) on average, however many keys there are. Python’s dict and set are hash maps.

01 — one item first

Start with one put.

Eight buckets and one key. Watch the key become a number, the number pick a bucket, and get jump straight back to it.

handed back:

Python

# Node(key, value, next): lesson 1’s node plus a key
class HashMap:
def __init__(self):
self.buckets = [None] * 8
def _index(self, key):
h = sum(ord(c) for c in key) # toy hash
return h % len(self.buckets)
def put(self, key, value):
i = self._index(key)
node = self.buckets[i]
while node:
if node.key == key: # already here?
node.value = value
return
node = node.next
self.buckets[i] = Node(key, value, self.buckets[i])
def get(self, key):
node = self.buckets[self._index(key)]
while node:
if node.key == key:
return node.value
node = node.next
raise KeyError(key)

02 — the reason it exists

Hash map vs list: find by key.

The same eight pairs, stored two ways. A list has to check pair after pair. A hash map does the sum and opens one bucket.

A list of pairs

looks: 0

A hash map

looks: 0

Pick a key to look for.

03 — when two keys collide

Hash collisions and chaining.

Eight buckets and endless possible keys: some must share. Here a bucket holds a small linked list, the one from lesson 1, and a new key is pushed on the front, like the stack in lesson 2.

handed back:

The map holds cat in bucket 0 and dog in bucket 2. Now put act.

04 — your turn

Put, get, delete.

Type a short key. Every button runs the class on the right, line by line, and tells you what it cost. Try owl or pig to make a collision.

handed back:

Pick a key and press a button.

Python

# Node(key, value, next): lesson 1’s node plus a key
class HashMap:
def __init__(self):
self.buckets = [None] * 8
def _index(self, key):
h = sum(ord(c) for c in key) # toy hash
return h % len(self.buckets)
def put(self, key, value):
i = self._index(key)
node = self.buckets[i]
while node:
if node.key == key: # already here?
node.value = value
return
node = node.next
self.buckets[i] = Node(key, value, self.buckets[i])
def get(self, key):
node = self.buckets[self._index(key)]
while node:
if node.key == key:
return node.value
node = node.next
raise KeyError(key)
def delete(self, key):
i = self._index(key)
prev, node = None, self.buckets[i]
while node:
if node.key == key:
if prev: prev.next = node.next
else: self.buckets[i] = node.next
return
prev, node = node, node.next
raise KeyError(key)
Each operation ends with its cost here.

05 — the classic bug

The get that never checked.

A tempting shortcut: jump to the bucket and return the first value there. It passes the obvious tests, where every key has a bucket to itself. When two keys share one, it hands back the wrong key’s value, with no error at all.

handed back:

cat and act share bucket 0, with act in front. Ask for get("cat"), two ways.

Buggy

def get(self, key):
node = self.buckets[self._index(key)]
return node.value # never checks node.key

Fixed

def get(self, key):
node = self.buckets[self._index(key)]
while node:
if node.key == key: # the missing check
return node.value
node = node.next
raise KeyError(key)

06 — load factor

Load factor and resizing: when the buckets fill, double them.

The load factor is keys ÷ buckets. Past a limit (0.75 here; Python’s dict uses about 0.67), chains get long, so the map makes twice as many buckets and moves every key, because % 16 gives different answers from % 8.

8 buckets · bucket = hash % 8

Four keys in eight buckets. Keep adding.

07 — spot them in the wild

Hash map or not? Real examples.

A hash map is the answer whenever you look things up by an exact key. It is the wrong tool when you need order or “nearby”. Pick one for each, then read why.

Look up a phone number by name

Count how often each word appears

A leaderboard always sorted by score

Remove duplicate emails from a list

Find every name that starts with “Ra”

Remember the order things were added

Cache a slow function’s answer for each input

Find the smallest number, again and again

08 — the boss level

Two Sum with a hash map.

The most asked interview question there is: find two numbers that add up to a target. Checking every pair is O(n²). Instead, for each number ask the map one question: have I already seen the number that completes it?

seen = {number: index} · bucket = n % 8

Python

def two_sum(nums, target):
seen = {} # number -> index
for i, n in enumerate(nums):
need = target - n
if need in seen: # one jump: O(1)
return [seen[need], i]
seen[n] = i
return None
Time O(n): one pass, and each in seen is one jump. Checking every pair is O(n²): 4,950 pairs for 100 numbers. Memory O(n) for the map.

09 — cheat sheet

Hash map time complexity.

Fast on average, slow only when keys pile into one bucket. In Python you rarely build one: dict, set, Counter and defaultdict are already hash maps.

JobAverageWorstIn Python
Put, get, delete by keyO(1)O(n)every key in one bucketd[k] = v, d[k], d.get(k), del d[k]
Is this key here?O(1)O(n)k in d, k in my_set
Grow and rehashO(1)spread over all puts (amortized)O(n)the one put that triggers itautomatic
Count thingsO(n)one passcollections.Counter(words)
Group things into listsO(n)one passdefaultdict(list), then groups[k].append(x)
Visit every pairO(n)for k, v in d.items()in insertion order, since Python 3.7
Smallest key, sorted keys, keys near XO(n) / O(n log n)hashing scatters ordermin(d), sorted(d); a heap or sorted list does this better

Two honest footnotes. Python’s dict handles collisions by probing for another free bucket (open addressing) rather than chaining, and it hashes strings with SipHash, which mixes every bit. The idea, and the costs, are the same.

Back a lessonStacks and queuesUp nextBinary trees