Hashing, from a coat check to fast lookup and caches
Place keys into buckets by hand, build a chaining hash map in Python, and reuse that map as a cache that returns a stored answer instead of computing it again.
November 12, 2026 · 12 min read · 210 views
Read
A hash function turns a key, such as a word, into a bucket number so a program can look in that one slot instead of scanning a whole list, which is how a dictionary finds a stored value and how a cache reuses an answer it already computed.
You will need. Reading an item from a list by its position · A key paired with a value, such as a name and a phone number · A short Python function, a for loop, and a list
The full lesson
Level 1 · Beginner: A lookup in one bucket
Start with five empty buckets numbered 0, 1, 2, 3, and 4. The hash of a lowercase word adds each letter's place in the alphabet, with a as 1 and b as 2, then keeps the remainder after dividing by 5. In the code that place is ord of the letter minus ord of a, plus 1, where ord is the number stored for that character. For ant the places are 1, 14, and 20, the sum is 35, and the remainder is 0, so ant sits in bucket 0.
Place dog next. The letters d, o, and g are places 4, 15, and 7, and those add to 26. Dividing 26 by 5 leaves remainder 1, so dog sits alone in bucket 1. Buckets 2 and 3 stay empty.
Place cat. The letters c, a, and t are places 3, 1, and 20, and those add to 24. Dividing 24 by 5 leaves remainder 4, so cat sits in bucket 4.
Place tac. The letters t, a, and c are places 20, 1, and 3, which also add to 24, so the remainder is 4 again. tac is added at the end of bucket 4, behind cat. Adding at the end of a list is what append does in the code. That shared bucket is a collision, and both keys stay.
Look up cat. Its places still add to 24, so the remainder is still 4, and only bucket 4 is read. The chain there is cat then tac, and cat is the first item, so the lookup hits and returns cat.
Look up owl. The letters o, w, and l are places 15, 23, and 12, which add to 50. Dividing 50 by 5 leaves remainder 0, and bucket 0 holds ant but not owl. The lookup misses and returns None, Python's name for no result, without reading the other four buckets.
Five buckets, four keys, a hit on cat and a miss on owl
def bucket(key): total = 0 for ch in key: total = total + ord(ch) - ord("a") + 1 return total % 5table = [[], [], [], [], []]for key in ["ant", "dog", "cat", "tac"]: table[bucket(key)].append(key)def find(key): chain = table[bucket(key)] for item in chain: if item == key: return key return Noneprint(table)print(find("cat"))print(find("owl"))Key takeaways
The hash picks one bucket, so the lookup skips the other buckets.
A collision keeps both keys, one after the other, in that bucket.
The same word always lands in the same bucket.
Level 2 · Intermediate: A map that chains collisions
A hash map stores pairs in buckets, and each bucket is a chain, a list of pairs. A pair is a two-item list: the key, then the value. The bucket number is a running total over the characters of the key. Start at 0, and for each character replace the total with 31 times the total plus ord of that character, then keep the remainder after dividing by the number of buckets. This table has eight buckets. The same key always produces the same total, so it always lands in the same bucket.
put writes one pair. It takes the chain for that key's bucket. range of the chain's length walks each position, and len is that length. If a pair's first item is the key, the pair is replaced with the key and the new value, and the chain does not grow. If the key is not there, append adds a new pair at the end. cat and tac are different keys with the same bucket number, so both pairs sit in one chain.
get reads one pair. It takes the same chain and walks it from the front. The second item of the first pair whose key matches is the answer. If the walk ends with no match, get returns None, the same no-result value as the missed lookup of owl.
Before any put, every chain is empty, so get on any key returns None. The empty string is still a key. It has no characters, the running total stays 0, and the pair is stored in bucket 0, where a later get finds it.
A second put of an existing key replaces the value and leaves a single pair. put of cat with 1, then put of cat with 2, leaves the value 2. tac falls in cat's bucket and keeps its own value, 4. nope falls in that same bucket but was never stored, so the walk passes cat and tac and returns None. dog falls in a different bucket, and get returns the value that was stored for it.
The script checks each of those cases with assert. An assertion stops the program when the comparison is false. The checks are a get on the empty map, the replaced value of cat, the colliding key tac, dog in another bucket, the missing key nope, and the empty-string key.
Chaining map checked for empty, duplicate, collision, and missing keys
class HashMap: def __init__(self): self.size = 8 self.buckets = [[], [], [], [], [], [], [], []] def _index(self, key): total = 0 for ch in str(key): total = (total * 31 + ord(ch)) % self.size return total def put(self, key, value): chain = self.buckets[self._index(key)] for i in range(len(chain)): if chain[i][0] == key: chain[i] = [key, value] return chain.append([key, value]) def get(self, key): chain = self.buckets[self._index(key)] for pair in chain: if pair[0] == key: return pair[1] return Nonestore = HashMap()assert store.get("missing") is Nonestore.put("cat", 1)store.put("cat", 2)store.put("tac", 4)assert store._index("cat") == store._index("tac") == store._index("nope")assert store.get("cat") == 2assert store.get("tac") == 4store.put("dog", 3)assert store._index("dog") != store._index("cat")assert store.get("dog") == 3assert store.get("nope") is Nonestore.put("", "blank")assert store.get("") == "blank"print("ok")Key takeaways
put replaces the value when the key is already in the chain.
A collision stores both pairs in one chain, and each get returns its own value.
get returns None when the chain has no pair with that key.
An empty string is a real key and lives in bucket 0.
Level 3 · Advanced: A cache on the same map
A cache is a hash map from a key to an answer that was costly to compute. The first request for a key is a miss: the answer is computed and then stored. A later request for that same key is a hit: the stored answer comes back and the computation does not run again.
The cache below is a dict, the hash map that comes with Python. It is the same idea as the chaining table: a key is turned into a bucket number and the value is kept there. Asking whether the key is in the dict is the lookup, and assigning the dict at that key is the store. The language's map is used here so the new part, hit versus miss, is the only new idea.
square adds each input it actually computes to the end of a list named runs, then returns the number multiplied by itself. The first cached call with 4 stores 16, and runs holds only 4. The second call with 4 finds 4 already in the cache, returns 16, and runs stays a list of just 4. The call with 5 is a new key, so square runs again and runs ends as 4 followed by 5.
The load factor is the number of stored keys divided by the number of buckets. Chains stay short while that ratio stays under about 0.75. When it climbs past that, make a new table with twice as many buckets and put every pair in again. The bucket number depends on the table size, so the old indexes are not reused.
A larger table does not remove the unlucky case. A hash that sends every key to one bucket leaves a single chain holding all of the keys, and a lookup walks that whole chain. A caller who can choose the keys can force that pile-up when the hash is easy to predict, so a cache that accepts outside keys needs a hash an outsider cannot steer.
Skip a hash map when the keys must come back in sorted order, because hashing does not arrange keys by size or by alphabet. Skip it for a handful of items too: scanning a short list is easier to read and just as fast. Hashing fits when many keys are fetched by identity and order does not matter.
A dict cache that computes each input once
cache = {}runs = []def square(n): runs.append(n) return n * ndef cached_square(n): if n in cache: return cache[n] value = square(n) cache[n] = value return valueassert cached_square(4) == 16assert runs == [4]assert cached_square(4) == 16assert runs == [4]assert cached_square(5) == 25assert runs == [4, 5]print("ok")Key takeaways
A miss computes the answer and stores it. A hit returns the stored answer.
Grow the table when the load factor passes about 0.75, and put every pair in again.
One bucket that holds every key makes a lookup walk all of them.
Use a hash map to fetch by key, not to keep keys in sorted order.
Complexity
Time: O(1) best, O(1) average, O(n) worst
Space: O(n) for the stored keys and values
A lookup hashes the key and walks only that bucket. When the hash spreads keys evenly and the load factor stays low, the walk is a few steps, so the time is O(1) on average and in the best case of a bucket with one pair. When every key lands in one bucket, the walk visits all n keys, so the time grows in line with n. The buckets and the stored pairs take space in line with the number of keys, which is O(n).
Common mistakes
Dropping the second key when two keys share a bucket. Append it to that bucket's chain, or one of the values is lost and a later lookup misses.
Appending a second pair when the key is already in the chain. Search the chain and replace the value, or a later get can return the stale one.
Treating None from get as a stored answer. None also means the key was never stored, so a computed result of None is calculated again on every call. Keep a separate marker that means hit.
Leaving the table at its first size after many puts. Chains grow with the keys. When stored keys pass about three quarters of the buckets, double the buckets and put every pair in again.
Choosing a hash map when the next step needs the keys in alphabetical or numeric order. Hashing does not provide that order. Sort a list of the keys, or use a structure that keeps them sorted.
Calling every lookup instant. A hash that spreads keys makes the usual lookup a few steps. A bucket that collects every key takes a walk that grows with the number of keys.
Practice problems
Place five new words into five buckets (easy). Hint: Use the letter-place sum from the hand example, divided by 5. Note which remainder shows up twice.
Delete one key and leave the rest of its chain (easy). Hint: Find the chain with the key's bucket number, then remove only the pair whose first item is that key.
Grow the table when the chains would lengthen (medium). Hint: Watch how many keys you have compared with how many buckets. A larger table gives every pair a new bucket number, so insert them again.
Count hits and misses for a cached function (medium). Hint: Call the cached function twice with one input and once with a different input. The stored input should not be computed a second time.
Compare a spreading hash with one constant bucket (hard). Hint: Make one bucket function return the same number for every key. Fill both maps with the same keys and compare how long a lookup takes as the maps grow.
Summary
The first level hashes each word into one of five buckets and reads only that bucket, keeping both words when they collide. The second level is a map: put replaces the value when the key is already in the chain, get returns None when it is not, and a short test checks an empty map, a duplicate, a collision, and a missing key. The third level stores computed answers in the same kind of map, so a repeated key is a hit and a new key is a miss, and chains stay short only while the load factor is low and the hash spreads keys. Hashing is why a dictionary and a cache can answer without scanning every item, and why that answer is a few steps on average and a full chain when every key shares one bucket.
Was this helpful?
Comments (0)
Sign in or create an account to join the conversation.
- No comments yet. Be the first!