Skip to the workspace
Pebellslearn by building
Foundations: Complexity & Arrays  ›  Lesson

Hash Tables & the Song Index

Hash Tables 22 minTurning a key into an address for O(1) lookups

dsa / Hash Tables & the Song Index

Explore each scene at your own pace.

01 · Look up track t48213 instantly

Look up track t48213 instantly

Hash Tables & the Song Index

Definition
A hash table stores key-value pairs by running each key through a hash function to get a bucket number, so storing and finding a key both jump straight to that bucket, taking O(1) time on average.
In plain words
It works like a coat check: your ticket number tells the attendant exactly which hook holds your coat, so no one searches the whole room. Sometimes two tickets point at the same hook, so each hook has to cope with sharing.

In short: a hash table turns a key into the address where its value lives, instead of searching for it. A hash function maps the key to an integer, % size folds that into a bucket number, and storing or finding a key both jump straight to that bucket. Two different keys can land in the same bucket — a collision — so a bucket must be able to hold more than one entry, or probe onward to find a free one. With a decent hash and a bounded load, that's O(1) on average. Python's dict and set are hash tables.

Two shelves side by side: a plain list of 6 tracks all greyed-out except the one being scanned, versus one bucket arrow pointing straight at the right track — 'scan every slot' vs 'jump straight there'

Look up track t48213 instantly

With 10 million tracks in a list, finding one by id means checking them in turn — O(n), on every play. A hash table skips the search entirely:

python

The mistake a toy hash makes: ignoring character order. "Nova" and "Avon" add up to the same total, so they collide every time:

What does this print?
def toy_hash(key):
    return sum(ord(ch) for ch in key)

print(toy_hash("Nova") % 8 == toy_hash("Avon") % 8)

Python's hash() does this properly, and randomises a string's hash per process so nobody can pre-compute keys that collide. There are always more possible keys than buckets, so collisions still happen — two classic fixes: chaining (each bucket holds a small list of pairs) and open addressing (a taken bucket makes you probe onward to the next free one; CPython's dict/set use this). Filing five ids into 8 buckets with open addressing:

your code, drawn · array

Open addressing: a key whose bucket is taken probes onward, so collisions make every later lookup on that stretch walk further.

A chained lookup hashes once, then walks only that bucket's chain — never the rest of the table:

watch it move · grid

A lookup hashes straight to one bucket and walks only that chain, so its cost depends on the chain length, not on the size of the table.

Looking up key 5: 5 % 4 = 1, so the lookup goes straight to bucket 1 and never touches the other three. 4 by 2 table. 6 of 8 cells filled.

1 / 3

The load factor (entries / buckets) is the average chain length — how many comparisons a lookup expects. Past a threshold the table resizes: roughly doubles its buckets and rehashes every key. That's O(n) for one resize, but — exactly like append — rare enough to be amortized O(1) per insert:

What does this print?
entries, buckets, resizes = 0, 8, 0
for track in range(20):
    entries += 1
    if entries / buckets > 0.75:
        buckets *= 2
        resizes += 1
print(buckets, resizes)
Scene 1 of 8
Project context and further resources
You're building a piece ofTunebox — the library
This piece — build_index(): id → track lookups and artist grouping, instantly.
Scenario Scanning millions of tracks on every tap is too slow. The song index is a pair of hash tables — id → track and artist → tracks — that make "play this" and "everything by this artist" instant.
build_index.py
Call the function you wrote — just like your app's frontend would. Edit the inputs and hit Call.
build_index(tracks) → dictTwo lookups: id → title, and artist → titles in library order.
try:
returned
Press Run to execute your code.
Press Check to run the tests for this lesson.
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.