Hash table — look up a key in the slot its hash names

A hash table finds a key by turning it into a slot number and reading that slot. It fits a collection that will be asked many times, when the only question is whether the key is present. It does not fit a single query, a request for the next larger key, or a walk in stored order.


What problem it solves

A linear scan reads every item until the key matches or the sequence ends. Ask the same collection again and the scan repeats. A hash table pays for one pass that stores each key, then answers later questions from the slot the key names.

Take [4, 2, 7, 3, 9] and five slots, numbered 0 to 4. The hash here is the remainder modulo 5: the slot is value % 5.

value remainder slot
4 4 4
2 2 2
7 2 2
3 3 3
9 4 4

7 and 2 name the same slot. So do 9 and 4. A slot that already holds a key keeps a short chain. The table after that one pass is:

0:  (empty)
1:  (empty)
2:  2 → 7
3:  3
4:  4 → 9

Building it read each of the five keys once. That preparation is Θ(n).

A later lookup hashes the key and reads only that chain. 3 names slot 3, and the first key there is 3. 7 names slot 2, which starts with 2 and then holds 7. 8 also names slot 3, the chain ends at 3, and 8 is absent. 1 names slot 1, which is empty. None of these reads the other slots.

The chains are why the lookup expects constant time rather than promising it. A usable hash spreads keys, and the table grows when it gets crowded, so a chain stays a few keys long no matter how large n is. If every key landed in slot 2, that chain would be the whole set and the lookup would be a scan again. Expected Θ(1) means that pile-up is rare. The worst case is still Θ(n).

This remainder is a teaching hash. A hash of a string mixes the characters and then takes a remainder. The two steps are the same: name a slot, then look only there. A cryptographic hash such as SHA-256 is a different job. It fingerprints a message. It does not choose a slot in a table.


Where it is used

A hash table is the usual structure behind a dictionary of keys.

  • Python’s dict and set, Java’s HashMap, and JavaScript’s Map store a key by hashing it and keep the record in that slot.
  • A database hash index answers WHERE id = 42 the same way. A range such as id > 42 wants an ordered index instead.
  • A cache keyed by a URL, and a compiler’s table of variable names, are hash tables. Repeated equality tests are the whole workload.
  • The scan in linear search is what you do before this table exists, or when the collection is short enough that the pass to build it costs more than the questions you will ask.

Drop it when you will ask once. The build is already a full pass, and one scan would have answered. Drop it when the question is the next key, a range, or a prefix. Those need an ordered tree or a trie. Keep it when the same set of keys will be tested for equality many times.


Working code

HashTable uses key % 5 and a chain in each slot. After inserting 4, 2, 7, 3, 9, the slots are [[], [], [2, 7], [3], [4, 9]]. Membership then follows one chain: 3 and 7 are present, 8 and 1 are not.

class HashTable:
    def __init__(self, n_slots):
        self.slots = [[] for _ in range(n_slots)]

    def add(self, key):
        chain = self.slots[key % len(self.slots)]
        if key not in chain:
            chain.append(key)

    def __contains__(self, key):
        return key in self.slots[key % len(self.slots)]


table = HashTable(5)
for value in (4, 2, 7, 3, 9):
    table.add(value)

assert table.slots == [[], [], [2, 7], [3], [4, 9]]
assert 3 in table
assert 7 in table
assert 8 not in table
assert 1 not in table
print(table.slots)

本文由 HoHo 與 AI 協作整理,最後更新於 2026 年 11 月 21 日。

Leave a Reply

Your email address will not be published. Required fields are marked *