Hash Tables & the Song Index
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.

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:
The mistake a toy hash makes: ignoring character order. "Nova" and "Avon" add up to the same total, so they collide every time:
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:
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:
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.
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:
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)