iq.lab
Python starts when a code cell comes near or you run one
03 Arrays and hash maps

Lesson 2 of 5

How a hash map works

A dict or a set finds a key without searching everything it holds. The key's hash picks one bucket, and only that bucket is searched. Watch the buckets fill, collide and double, and learn why lookups are O(1) on average and O(n) at worst.

About 1 hour 25 minutes
By the end you can
  • Work out which bucket a key lands in from its hash and the number of buckets

  • Explain why a lookup searches only one bucket, and what a collision costs

  • Explain load factor and resizing, and state the average and worst-case cost of a lookup

  • Say which values can be dict keys and why a list cannot

  • Count and group with .get, Counter and defaultdict

Your team keeps 50,000 user names, and a sign-up form asks: is "owl" taken? Kept in a list, the names can only be compared one at a time, from the left, so a name that is not there costs 50,000 comparisons. Kept in a set, the same question costs about one. Module 2 gave you the price: x in a_list is O(n), and x in a_set is O(1) on average. (O(n) means the work grows in step with n, the number of items; O(1) means a fixed amount of work, whatever n is.)

This lesson opens the box. How can a set answer without searching? The idea fits in one sentence: work out where the key must be, from the key itself, and look only there. Python's dicts and sets are built on it, and so is every hash join you have run. The details (collisions, resizing, and why a list cannot be a key) are what you need when an interviewer asks whether a lookup is really O(1).

A key's place, computed from the key

Where should a key go so that we can find it again without searching? Picture a row of buckets: numbered places to keep keys, here 8 of them, numbered 0 to 7. In code the row is a list, so reaching bucket 5 is one step: the slot arithmetic from the previous lesson. To store a key, we need a rule that names its bucket. A hash function is a rule that turns a key into a whole number, called the key's hash. It must always give the same key the same number, or a later lookup of a stored key could search the wrong bucket.

The bucket is the remainder of the hash divided by the number of buckets. In Python that is h % 8. The % operator gives the remainder after division: 19 is 2 × 8 + 3, so 19 % 8 is 3. A remainder after dividing by 8 is always one of 0 to 7, so every hash picks a real bucket.

This lesson uses a made-up teaching hash, simple enough to work out by hand. ord(ch) gives the code number Python uses for the character ch: ord("a") is 97, ord("c") is 99, ord("t") is 116. Multiply each character's code by its position plus 1, and add them up. Positions count from 0, so the first character is multiplied by 1, the second by 2, the third by 3. Before you step through, guess: which of the 8 buckets does "cat" land in?

Step throughFrom a key to a bucket
Step 1 of 14
Line 1 is about to run.
def teaching_hash(key):
h = 0
for i, ch in enumerate(key):
h += (i + 1) * ord(ch)
return h
h = teaching_hash("cat")
print(h, h % 8)
Names
no names yet
Output
(nothing printed yet)

Every later question about "cat" does the same arithmetic, gets bucket 1 again, and looks only there. That is the whole trick. A list has no way to know where a value is; a hash table computes it.

Work it outWhich bucket?

Use the teaching hash from the trace: each character's code times its position plus 1, added up. With 8 buckets, which bucket does "dog" land in? The codes are ord("d") = 100, ord("o") = 111 and ord("g") = 103. Type a whole number from 0 to 7.

bucket

Type a number: 12, -1, 0.5 and 3/4 all work. Enter checks.

Python's built-in hash() plays the same role. For a string its rule is far more scrambled: it gives a large number, sometimes negative, and the number changes each time Python starts (a defense against attackers who send keys chosen to collide). Within one run the same string always gets the same number, which is all a table needs. (% by a positive number never gives a negative answer in Python, so the bucket is still 0 to 7.) For a small whole number, hash(n) is n itself: hash(5) is 5. That keeps the next traces checkable by hand.

Two keys, one bucket

What happens when two keys pick the same bucket? There are 8 buckets and endless possible keys, so some keys must share a bucket. "god" has the hash 1 × 103 + 2 × 111 + 3 × 100 = 625, and 625 % 8 is 1: the same bucket as "cat". Two different keys in one bucket is called a collision.

The usual fix is to let each bucket hold a short list of its keys, called its chain. This design is called chaining. To add a key, find its bucket and append the key to that chain (a set keeps one copy, so skip it if it is already there). To look a key up, find its bucket and compare the key with each item in that chain, and nowhere else.

The trace builds that table in Python: a list of 4 lists, one per bucket, drawn as a grid with one row per bucket. The keys are small whole numbers, so hash(key) is the key itself and the bucket is key % 4. Guess first: which two keys share a bucket, and how many comparisons does contains(buckets, 13) make?

Step throughA hash table with chains
Step 1 of 41
Line 1 is about to run.
def add(buckets, key):
chain = buckets[hash(key) % len(buckets)]
if key not in chain:
chain.append(key)
def contains(buckets, key):
chain = buckets[hash(key) % len(buckets)]
for item in chain:
if item == key:
return True
return False
buckets = [[], [], [], []]
for key in [5, 9, 2]:
add(buckets, key)
print(buckets)
print(contains(buckets, 9))
print(contains(buckets, 13))
Names
no names yet
Output
(nothing printed yet)

One bucket is enough because of a promise the table keeps: add puts every key in the bucket its hash picks. So if 13 were anywhere in the table, it would be in bucket 1. Bucket 1 does not have it, so the table does not have it.

The widget below is the same idea with string keys and the teaching hash: 8 buckets, already holding "cat", "dog", "act" and "god". Each row is a bucket; keys in one bucket are joined by arrows into a chain. A panel shows the hash arithmetic for the current step's key. Guess first: how many keys does a lookup of "god" compare?

Try a table by hand before you write the lookup yourself.

On paperA table by hand

On paper, draw 4 empty buckets numbered 0 to 3. Add the keys 6, 10, 3, 14, in that order, the way add does in the trace: the bucket is key % 4, and a key joins the end of its bucket's chain. Then look up 18. How many keys does the lookup compare before it can say "not found"? Reveal one step at a time to check your table.

Work it on real paper: writing each step is the point. Then check your final answer here and compare your working with the walk-through.

comparisons for 18

Type a number: 12, -1, 0.5 and 3/4 all work. Enter checks.

Code itLook in one bucket

Write contains(buckets, key) for a table like the one in the trace. buckets is a list of chains (lists), and every stored key was put in the chain at position hash(key) % len(buckets). Return True if key is stored and False if not.

Search only the one bucket the key can be in. One test plants a key in the wrong bucket on purpose: a correct lookup never sees it, because the promise says it cannot be there. Then press Watch it run.

⌘+Enter runsPython starts when a code cell comes near or you run one
Write your code where the starter says raise NotImplementedError, then press Run tests. Each check says what it expects.

Keeping chains short

A lookup costs one comparison per key in its chain. So what stops the chains from growing long? If the table kept 8 buckets while 80 keys arrived, the chains would average 10 keys, and with 8,000 keys, 1,000. With a fixed number of buckets, the chains grow in step with n, and lookup becomes O(n).

The load factor is the number of keys divided by the number of buckets: 4 keys in 8 buckets is 0.50. It is the average chain length, with an empty bucket counted as a chain of length 0. The table keeps it low by growing. When an add would push the load factor above a limit (0.75 in this lesson), the table first doubles its buckets and places every key again. Placing every key again is called rehashing. Every key needs its bucket worked out afresh, because the remainder can change when the number of buckets changes: 5 % 4 is 1, but 5 % 8 is 5.

The trace doubles a 4-bucket table whose keys 1, 5 and 9 all landed in bucket 1. Guess first: where does each key go when there are 8 buckets?

Step throughDoubling the buckets
Step 1 of 31
Line 1 is about to run.
def resize(buckets):
bigger = [[] for _ in range(2 * len(buckets))]
for chain in buckets:
for key in chain:
bigger[hash(key) % len(bigger)].append(key)
return bigger
buckets = [[], [1, 5, 9], [], []]
buckets = resize(buckets)
print(buckets)
Names
no names yet
Output
(nothing printed yet)

After doubling, each key either keeps its bucket number or moves up by the old number of buckets: 1 and 9 stayed in bucket 1, and 5 moved from 1 to 5, which is 1 + 4.

Put in orderDouble the buckets

Put the lines in order to build resize(buckets), which returns a new table with twice as many buckets and every key placed again. Indentation is part of each line. Two lines do not belong.

Your program

Add lines from the list below, in order.

    Unused lines (some do not belong)
    • bigger = [[] for _ in range(2 * len(buckets))]
    • bigger[hash(key) % len(bigger)].append(key)
    • return buckets
    • for key in chain:
    • for chain in buckets:
    • def resize(buckets):
    • return bigger
    • bigger[hash(key) % len(buckets)].append(key)

    The widget holds 6 keys in 8 buckets, a load factor of exactly 0.75. A seventh key would make it 7 ÷ 8 = 0.875, above the limit, so the next add doubles the table first. Guess first: after the doubling, do "cat" and "god" still share a bucket? Their hashes are 641 and 625.

    So what does a lookup cost? With a hash that scatters keys evenly, the average chain holds at most 0.75 keys, so a lookup or an add is O(1) on average. A rehash touches every key, O(n) for that one add, but it is rare: the table doubles each time, so each rehash moves twice as many keys as the one before, and over n adds all the rehashes together move fewer than 2n keys. That is the same argument that makes append cheap on average in the previous lesson: adds are amortized O(1), meaning O(1) when averaged over a long run of operations.

    The worst case is O(n). If many keys share one bucket, as "cat", "god" and "owl" do above, a lookup must compare them all. With all n keys in one chain, a lookup walks the whole table, no faster than a list. A hash that scatters keys well makes this rare with ordinary data. Python's own dict and set follow the same plan with different details: instead of chains, they put a colliding key in another free slot of the same table, and they choose their own resize limit. The costs come out the same: O(1) on average, O(n) at worst.

    One more detail: computing a hash reads the whole key. The first trace took one step per character, and so does Python's hash() on a string. For numbers and short words that cost is small and fixed, so we call a lookup O(1). A key of k characters costs O(k) to hash: with long keys, say so.

    Quick checkWhen every key collides

    A chained table like the ones in this lesson has 8 buckets and holds the keys 0, 8, 16, 24, 32 and 40 (small whole numbers, so each hash is the key itself). How many keys does a lookup of 48 compare, and why?

    Choose one answer, then check.

    Recap. A key's hash picks its bucket, and a lookup searches only that bucket. Collisions make chains, the load factor is the average chain length, and doubling the buckets keeps it at most 0.75. That gives O(1) on average and O(n) when keys pile into one bucket.

    What can be a key

    {[1, 2]: "x"} fails with a TypeError. Why would Python refuse a list as a key? Suppose it allowed one, with a list's hash being the sum of its items. The trace stores the list [1, 2] in a 4-bucket table, then changes the list. Guess first: does a lookup of the same list find it?

    Step throughA key that changes after it is stored
    Step 1 of 7
    Line 1 is about to run.
    buckets = [[], [], [], []]
    key = [1, 2]
    buckets[sum(key) % 4].append(key)
    key.append(3)
    print(key in buckets[sum(key) % 4])
    print(key in buckets[3])
    Names
    no names yet
    Output
    (nothing printed yet)

    A key's hash must never change while the key is stored. So a key must be immutable: a value that cannot be changed after it is made. Numbers, strings, and tuples of them are immutable, so they are hashable: they have a hash that stays the same forever. Lists, dicts and sets can change, so Python refuses them: d[[1, 2]] = "x" raises TypeError: cannot use 'list' as a dict key (unhashable type: 'list'). The items of a set are its keys, so {[1, 2]} is refused the same way. Only keys are hashed, so a value can be anything: d["ana"] = [1, 2] is fine, and the grouping trace at the end of this lesson stores lists as values.

    When you need a list as a key, turn it into a tuple first: tuple([1, 2]) is (1, 2), and d[(1, 2)] = "x" works. Grouping problems need this move: a tuple of letter counts can be a key, and a list of them cannot. A tuple only counts if everything inside it is hashable: (1, [2]) holds a list, so it is refused too.

    Quick checkWhy not a list?

    Python refuses d[[1, 2]] = "x" with TypeError: cannot use 'list' as a dict key (unhashable type: 'list'). Why can a list not be a dict key?

    Choose one answer, then check.

    Dicts, sets and counting tools

    How does a dict differ from a set? A set stores keys. A dict stores a value with each key. Inside, they work the same way: a dict keeps each value next to its key, so finding the key finds the value. seen = set(), seen.add(x) and x in seen are the set moves. ages = {}, ages["ana"] = 31 (store a value) and ages["ana"] (read it) are the dict moves. "ana" in ages asks about the keys only, never the values, and costs one bucket search like any other lookup.

    Reading a key that is not there, d[k], raises a KeyError. That matters for counting, where each new word needs a count to start from. d.get(k, 0) returns the value for k if k is a key, and 0 if it is not. Guess first: what does counts hold at the end?

    Step throughCounting with get
    Step 1 of 11
    Line 1 is about to run.
    words = ["cat", "dog", "cat"]
    counts = {}
    for w in words:
    counts[w] = counts.get(w, 0) + 1
    print(counts)
    Names
    no names yet
    Output
    (nothing printed yet)

    Two tools from collections do the same job with less typing. collections is a module (a file of ready-made code) that comes with Python, and from collections import Counter, defaultdict brings in both names. This lab's cells already have them, but write the import anyway, as you would in an interview.

    A defaultdict(int) is a dict that gives a missing key the value int(), which is 0, the first time you look it up with counts[k]. A Counter does the whole counting walk in one call. Both give the same counts as the trace:

    from collections import Counter, defaultdict
    
    counts = defaultdict(int)
    for w in ["cat", "dog", "cat"]:
        counts[w] += 1              # a missing key starts at 0
    print(counts["cat"])            # 2
    
    counts = Counter(["cat", "dog", "cat"])
    print(counts["cat"], counts["owl"])   # 2 0: a Counter gives 0 for a missing key

    Either is fine in an interview. If you use Counter, be ready to say what it does underneath: the same walk as the get loop, one count per item.

    PredictCounting letters

    A string is a sequence of characters, so Counter counts its letters. A Counter prints like a dict wrapped in Counter(...), with the largest counts first: Counter({'x': 2, 'y': 1}). Type exactly what this prints, both lines.

    from collections import Counter
    
    c = Counter("banana")
    print(c)
    print(c["a"], c["z"])
    

    defaultdict(list) gives a missing key an empty list, which is what grouping needs: each key collects the items that share it. Guess first: which words end up under "c"?

    Step throughGrouping with defaultdict(list)
    Step 1 of 11
    Line 1 is about to run.
    from collections import defaultdict
    groups = defaultdict(list)
    for w in ["cat", "dog", "cow"]:
    groups[w[0]].append(w)
    print(dict(groups))
    Names
    no names yet
    Output
    (nothing printed yet)

    A list under a key can collect anything, not only the items themselves. Collect positions instead, with each word as its own key:

    Code itWhere each word appears

    Write positions(words), which returns a dict from each word to the list of positions where it appears, in increasing order. For ["cat", "dog", "cat"] the answer is {"cat": [0, 2], "dog": [1]}. Use defaultdict(list) or a plain dict. A defaultdict compares equal to a plain dict with the same keys and values, so either passes. Then press Watch it run.

    ⌘+Enter runsPython starts when a code cell comes near or you run one
    Write your code where the starter says raise NotImplementedError, then press Run tests. Each check says what it expects.

    Last, say it out loud. The words you write here are the words you will use in the room.

    Say itIs a dict lookup really O(1)?

    Your plan uses a dict, and the interviewer asks: "You said a dict lookup is O(1). Is it always?" Write what you would say, in a few plain sentences: how the lookup works, why it is fast on average, and when it is not.

    A few sentences first: 0 of 60 characters.

    Saved in this browser as you type.

    Next: Counting and seen-before