Hash tables: jump straight to a key's slot

If your locker key has a number on it, you do not open every locker from the first one. A hash table turns a key (a name) into a number and uses that number to work out the slot right away. Follow one word as it becomes a number, then a slot number, then lands in its slot, one step at a time.

Short answer. A hash table is a table that turns a key into a number (the hash function) and uses that number to pick a slot right away. Putting and finding do the same calculation, so you look at one slot instead of the whole table. Usually you find a key in one or two compares. When many keys land in one slot (collisions) it slows down, and at worst it compares all n keys. Python's dict and set find their slots from the key's hash value.

    Press "Next" to move one step. The gray box on top shows the word and the calculation for that step, and the box below says what was looked at, what was done, and why. Arrows point at the one thing that step did. Blue arrows go word → hash value and calculation → slot, the orange arrow and "≠" mark the word being compared, the green arrow marks a word just put in or just found, and the black arrow marks the end of the chain (not there). The blue outline marks the slot being looked at, and "already here" marks words that were in the slot before the new word arrived. Type 1 to 8 letters from a to z in the Word box and press "Put" or "Find" to add that job's steps to the end. Try these made-up words: mok, zel, rua, tib, pim, har, nul, vio, kesa, dop.

    Try this. ① Press "Next" 24 times. Six words go in, then tib is found. In slot 4 it is compared with mok, then found at tib: 2 compares. ② Press "Find" with nul in the Word box. Its hash value is 92, so slot 4. It is compared with mok and tib, the chain ends, and the answer is "not there". No other slot is checked. ③ Put kesa, then dop. The letters are completely different, but both hash to 82, so they hang on the same chain in slot 2. ④ Put mok again. It is found in slot 4, so nothing new goes in.

    Definitions

    The sections below explain with a toy hash function and experiments. The textbook definitions are these. m is the number of slots (buckets), n is the number of keys put in, and slot numbers run from 0 to m − 1.

    hash table
    A data structure that stores keys (and the values attached to them) in an array of m slots, where the slot for each key is a slot number computed from the key. Putting in and finding do the same computation, so only that slot is checked.
    hash function
    A function that turns a key k into an integer, the hash value h(k). It always gives the same hash value for the same key. This page uses the remainder of the hash value divided by the number of slots as the slot number (modular hashing).

    i=h(k)modm

    collision
    Two different keys getting the same slot number. It must happen when there are more keys than slots, so a hash table always comes with a rule for handling collisions.

    k1≠k2,h(k1)modm=h(k2)modm

    separate chaining, open addressing
    Two ways to handle collisions. Separate chaining keeps a list (a chain) in each slot and hangs every key that lands in that slot on its list. Open addressing stores each key directly in a slot, one key per slot, and if the slot is taken, it probes other slots in a fixed order and uses the first empty one. Linear probing, which goes to the next slot and then the one after, checks slots in this order:

    (h(k)+j)modm(j=0,1,2,…)

    load factor
    The number of keys put in divided by the number of slots, written α. With separate chaining it equals the average chain length and can be more than 1. With open addressing each slot holds one key, so it must stay below 1.

    α=nm

    rehashing
    Making a new table with a different number of slots (often twice as many), computing every key's slot number again with the new number of slots, and moving the keys over. It is done to bring the load factor down.

    1. What a hash table is: turn the key into a number, use it as the slot

    An array opens a slot by its number (0, 1, 2 …). To open slot 7 you do not scan from slot 0. But what we usually have is a name (a key), not a number: a user ID, a word, a product code. A hash table fixes one calculation that turns a name into a number, and puts the item in that numbered slot. To find it, do the same calculation, get the same slot, and look only there.

    The calculation that turns a name into a number is the hash function, and the number it gives is the hash value. Hash values can be large, so the slot number is the remainder after dividing by the number of slots. The remainder is always 0 to (slots − 1), so it always lands on a real slot. The toy hash function on this page works like this:

    hash value  = (1st letter number × 1) + (2nd letter number × 2) + (3rd letter number × 3) + …   (a = 1, b = 2, … z = 26)
    slot number = remainder of hash value ÷ number of slots                                          (hash value % slots)
    
    put:  get the slot number → compare with the keys on that slot's chain → if not there, hang it at the end
    find: get the slot number → compare along that slot's chain from the front → same key: found; chain ends: not there

    Multiplying by the position mixes in the order of the letters. If you only added the letter numbers, mok and kom would get the same value (with positions they get 76 and 80). Real hash functions also mix in letter positions. One common way: multiply the value so far by a small prime such as 31, then add the next letter (section 3.4 of algs4 in the sources). The function on this page is built to be easy to follow by hand, so it is not very good at spreading keys evenly.

    2. Follow it by hand

    Put six made-up words, in order, into an empty table with 8 slots, then find tib. This is the same order the experiment starts with.

    Word to putLetter number × positionHash valueRemainder ÷ 8 = slotThat slot's chain after (why)
    mok13×1 + 15×2 + 11×3764mok (slot was empty)
    zel26×1 + 5×2 + 12×3720zel (slot was empty)
    rua18×1 + 21×2 + 1×3637rua (slot was empty)
    tib20×1 + 9×2 + 2×3444 (collision)mok → tib (mok ≠ tib, so hang it at the end)
    pim16×1 + 9×2 + 13×3731pim (slot was empty)
    har8×1 + 1×2 + 18×3640 (collision)zel → har (zel ≠ har, so hang it at the end)
    1. 76 ÷ 8 = 9 remainder 4. mok goes into slot 4. zel and rua, with hash values 72 and 63, go to slots 0 and 7.
    2. tib hashes to 44, and 44 ÷ 8 = 5 remainder 4. Slot 4 already holds mok. Two different keys landing in the same slot is a collision. Compare with mok, see it is a different word, and hang tib after mok.
    3. har: 64 ÷ 8 = 8 remainder 0. It hangs after zel in slot 0.
    4. Find tib. Work out 44 and remainder 4 again, and go to slot 4. The first word on the chain, mok, is different. The second, tib, is the same. 2 compares. The other seven slots were never touched.

    The finished table: slot 0 holds zel → har, slot 1 pim, slot 4 mok → tib, slot 7 rua, and the other four slots are empty. Finding each of the six words takes 1, 2, 1, 1, 1, 2 compares, so 8 ÷ 6 ≈ 1.33 on average.

    3. Collisions: hang a chain, or find the next empty slot

    With more keys than slots, collisions are certain. Even with fewer keys they happen by chance (the hand example put in six words and collided twice). So every hash table needs a rule for collisions. Two are common.

    MethodWhen puttingWhen findingLoad factor (keys ÷ slots)
    Chaining (this page's experiment)Each slot has a chain (a list). A key that lands there is hung on that chainCompare along that slot's chain from the frontCan go above 1. It is the average number of keys per chain
    Next empty slotIf the slot is taken, try the next slot, then the next … until an empty one, and put it thereStart at the same slot and compare while moving along. An empty slot means "not there"One key per slot, so it must stay below 1
    Chaining (this page's experiment) tib: 44 % 8 = 4 ① already here slot 4 mok tib ② hang it at the end Next empty slot tib: 44 % 8 = 4 ① already here ② slot 5 is empty: put it there mok tib slot 3 slot 4 slot 5 slot 6
    Two ways to handle a collision. tib's slot is 44 % 8 = 4, but mok got to slot 4 first (the hand example). Chaining hangs tib after mok. The next-empty-slot method finds slot 5 empty and puts tib there.

    The next-empty-slot method needs no separate chains, so memory is simpler. But runs of filled slots form clumps that slow it down, and deleting is harder: if you simply empty a slot, keys that were pushed past it can no longer be found. This page only experiments with chaining.

    4. Load factor and resizing

    With chaining, the load factor is number of keys n ÷ number of slots m. All the chain lengths add up to n, so the load factor is exactly the average chain length. When keys spread evenly over the slots, the number of compares for a lookup grows in step with this average (Property L in algs4). So as keys pile up and the load factor rises, it slows down.

    The fix is to add slots and put everything in again. When the number of slots changes, hash value % slots changes too, so you cannot move the chains as they are: every key needs its slot number worked out again. One resize moves all n keys, which is a big job. But if you double the slots, you can put in that many more keys before the next resize, so the cost per put stays constant on average.

    8 slots slot 0's chain zel har 72 % 16 = 8 64 % 16 = 0 16 slots zel har slot 8 slot 0
    Resizing works out each key's slot again. With 8 slots, zel and har hang on the same chain in slot 0. With 16 slots, 72 % 16 = 8 and 64 % 16 = 0, so they split up into slot 8 and slot 0. That is why you cannot move a chain as it is.

    The words are 48 made-up words of 3 to 5 letters, from a random number generator with a fixed seed. Use the slider or the number box to choose how many of them, from the front, go in. The hash function is the same as in the first experiment. The vertical scale is always 0 to 9, so when you add slots you can see the bars shrink.

    Try this. ① It starts with 24 words in 8 slots: load factor 3, longest chain 6, and 2.33 compares on average to find a word that is in the table. ② Press "Double the slots" once: 16 slots, load factor 1.5, longest chain 5, 1.88 compares on average. Twice: 32 slots, 0.75, longest chain 3, 1.5 compares. Three times: 64 slots, 0.38, longest chain 3, 1.33 compares. The average gets close to 1, but 47 of the 64 slots are empty, and that memory is spent. ③ Go "Back to 8 slots" and raise the words to 48: load factor 6, longest chain 9, 3.81 compares on average.

    5. What to know

    PropertyIn plain wordsIn the experiment
    Usually only one slot is checkedIf keys spread evenly and the load factor is low, the number of compares barely grows as n grows (O(1): "n doubles, it stays the same"). Computing the hash value costs as much as the key's length1.33 compares on average with 64 slots
    At worst, n comparesIf every key lands in one slot, one chain holds all n keys, and finding is the same as scanning a list from the front (O(n): "n doubles, it doubles"). It happens with a weak hash function, or when someone puts in only keys that land in the same slot on purposekesa and dop in the first experiment
    A higher load factor is slowerThe average chain length is the load factor. Add slots and put everything in again, and it is fast again"Double the slots"
    No orderThe hash value picks the slot. Keys scatter with no link to their sorted ordermok in slot 4, zel in slot 0
    Keys must not changeIf a key changes after it goes in, its hash value changes and lookups go to a different slot"Keys must not change" below

    No order

    The slot number is a remainder of the hash value, so it has nothing to do with how big the key is. To find "the smallest key", "every key starting with b", or "keys between 100 and 200", you have to scan the whole table. If you do that often, use something that keeps order: a sorted array with binary search or a binary search tree. A Python dict does remember an order, but it is the order you put keys in (question 3 below).

    Keys must not change

    Say you put mok in slot 4, then quietly change the key to mox. Looking up mox gives a different hash value and a different slot, so you cannot find it even though it is sitting in slot 4. That is why Python does not accept values whose contents can change after they go in, like list or dict, as dict keys or set members. To use several values together as a key, use a tuple, which cannot change ({(3, 5): "road"}).

    6. Which one to use

    Four ways to "find one item by its key". n is the number of keys stored.

    MethodFind: best · usual · worstPut (usual)In order · range searchExtra memoryUse it when
    Scan an unsorted list from the front (x in list)1 · n · n
    (n doubles, time doubles: O(n))
    Append: 1No (sort it first)NoneThere are only a few items, or you mostly add and rarely search
    Sorted array + binary search1 · log n · log n
    (n doubles, one more step: O(log n))
    n (shift everything after it)YesNoneYou build it once and search often, or need range searches
    Binary search tree1 · log n · n
    (n if it leans to one side)
    log nYesTwo child links per keyYou add and remove and also need order (to stop it leaning, use a red-black tree)
    Hash table (dict, set)1 · 1 · n
    (usually a few compares whatever n is: O(1))
    1 (an occasional resize, constant on average)NoEmpty slots, chain linksFind by key, remove duplicates, count things

    Big O notation is on the time complexity page. The hash table's "usually 1" assumes the hash function spreads keys evenly (the Python wiki in the sources states the same assumption).

    7. In Python

    Chaining, written out directly, looks like this. The resizing part is left out to keep it short. hash() is the hash function Python gives you.

    class ChainedTable:
        def __init__(self, size=8):
            self.buckets = [[] for _ in range(size)]      # each slot: a chain of [key, value]
        def put(self, key, value):
            chain = self.buckets[hash(key) % len(self.buckets)]
            for pair in chain:
                if pair[0] == key:                          # same key: just replace the value
                    pair[1] = value
                    return
            chain.append([key, value])                      # not there: hang it at the end
        def get(self, key):
            for k, v in self.buckets[hash(key) % len(self.buckets)]:
                if k == key:
                    return v
            raise KeyError(key)

    In real code, use the built-in dict and set.

    ages = {"mok": 3, "tib": 5}     # dict: key → value
    ages["tib"]                     # 5
    "zel" in {"mok", "tib"}         # set: is it there? False

    Where it is used

    Common questions

    Why use a set instead of a list to check if something is there?

    A list compares from the front, one by one, so with n items it may look at all n. A set works out the slot from the key's hash value and only looks at that slot's short chain. So usually the number of compares barely grows as n grows. But in the bad case where keys pile into one slot, a set also looks at up to n.

    Why can't a list be a dict key?

    A list can change after you put it in. If its contents change, its hash value changes, the lookup goes to a different slot, and a key you really did put in can no longer be found. So Python does not accept values that can change, like list and dict, as keys. To use several values together as a key, use a tuple, which cannot change.

    Doesn't a Python dict keep its order?

    It does, but it keeps the order you put keys in, not sorted order. Since Python 3.7 the docs guarantee that a dict goes through its keys in insertion order. To see keys from smallest to largest, or to find a range like "keys between a and c", you have to sort them yourself. The docs describe a set as an unordered collection.

    Words

    Plain words used hereWhat books call it
    A table that turns a key into a number to pick a slotHash table, hash map. Holding key-value pairs: symbol table, mapping
    The calculation that turns a name into a number, and that numberHash function; hash value, hash code
    SlotBucket, slot
    Picking the slot by the remainderModular hashing
    Different keys landing in the same slotCollision
    Hanging a chainSeparate chaining
    Finding the next empty slotOpen addressing, linear probing
    How full it isLoad factor (α)
    Adding slots and putting everything in againRehashing, resizing
    A big job now and then, but constant on averageAmortized
    A value that cannot change, a value that has a hash valueImmutable, hashable

    Sources

    ← Binary searchBinary search trees →