TExcelTAD

Hash Tables

Searching an unsorted array takes O(n), a sorted one O(log n). A hash table does better: on average it finds, inserts and deletes in O(1), constant time, no matter how many items it holds. Python's dict and set are hash tables, and they are probably the most used data structures in all of programming.

The idea

A hash table is an array of buckets. A hash function turns each key into a number, and that number (modulo the number of buckets) tells you which bucket the key belongs in. To find a key later, you compute the same hash and look in that one bucket only, instead of searching everywhere.

text
key "Ada" --hash--> 262 --mod 7--> bucket 3

A simple hash function

For this lesson we use a very simple hash function: add up the character codes of the key and take the remainder after dividing by the table size. The animation uses the same function.

python · try it yourself
def simple_hash(key, size):
    return sum(ord(ch) for ch in key) % size

for name in ["Ada", "Bob", "Eve", "Zoe"]:
    codes = sum(ord(ch) for ch in name)
    print(f"{name}: codes sum to {codes}, {codes} mod 7 = {simple_hash(name, 7)}")
Ada: codes sum to 262, 262 mod 7 = 3
Bob: codes sum to 275, 275 mod 7 = 2
Eve: codes sum to 288, 288 mod 7 = 1
Zoe: codes sum to 302, 302 mod 7 = 1

"Eve" and "Zoe" both land in bucket 1. Two different keys with the same bucket is a collision. Collisions are unavoidable (there are more possible keys than buckets), so every hash table needs a strategy for them.

Collisions: chaining

The most common strategy is chaining: every bucket holds a small list (or linked list) of all the keys that hashed to it. Step through putting four names into a 7-bucket table, then looking some up and removing one:

Implementation

python · try it yourself
class HashTable:
    def __init__(self, size=7):
        self.buckets = [[] for _ in range(size)]

    def _index(self, key):
        return sum(ord(ch) for ch in key) % len(self.buckets)

    def put(self, key):
        bucket = self.buckets[self._index(key)]
        if key not in bucket:
            bucket.append(key)

    def contains(self, key):
        return key in self.buckets[self._index(key)]   # only one bucket is searched

    def remove(self, key):
        bucket = self.buckets[self._index(key)]
        if key in bucket:
            bucket.remove(key)

table = HashTable()
for name in ["Ada", "Bob", "Eve", "Zoe"]:
    table.put(name)
print(table.buckets)
print("Zoe?", table.contains("Zoe"), " Max?", table.contains("Max"))
table.remove("Eve")
print(table.buckets)
print("Zoe?", table.contains("Zoe"))
[[], ['Eve', 'Zoe'], ['Bob'], ['Ada'], [], [], []]
Zoe? True  Max? False
[[], ['Zoe'], ['Bob'], ['Ada'], [], [], []]
Zoe? True

The buckets match the animation: Eve and Zoe share bucket 1, and after removing Eve, Zoe is still found.

Why it is O(1) on average

Looking up a key costs one hash computation plus a search of one bucket. If the hash function spreads keys evenly, each bucket holds about n / m keys, where n is the number of keys and m the number of buckets. That ratio is the load factor. Real hash tables keep it below a constant (Python's dict resizes when it is about 2/3 full) by growing and re-inserting all keys, so the bucket searches stay short.

A bad hash function ruins this. Our "sum of codes" function gives the same hash to all anagrams, so it would perform badly on words like these:

python · try it yourself
def simple_hash(key, size):
    return sum(ord(ch) for ch in key) % size

words = ["listen", "silent", "enlist", "tinsel", "inlets"]
print([simple_hash(w, 101) for w in words])
print("python's hash spreads them:", len({hash(w) % 101 for w in words}) > 1)
[49, 49, 49, 49, 49]
python's hash spreads them: True

Good hash functions mix the characters' positions in as well, so similar keys land far apart. Python's hash() for strings is such a function (it is also randomised per process for security, so never print or store its values).

Collisions: open addressing

The other main strategy, open addressing, stores every key directly in the array. If the bucket is taken, it probes the next one (index + 1, wrapping around) until it finds a free slot. Lookups follow the same probe sequence.

python · try it yourself
def simple_hash(key, size):
    return sum(ord(ch) for ch in key) % size

size = 7
slots = [None] * size
for name in ["Ada", "Bob", "Eve", "Zoe", "Lea"]:
    i = simple_hash(name, size)
    probes = 1
    while slots[i] is not None:          # linear probing
        i = (i + 1) % size
        probes += 1
    slots[i] = name
    print(f"{name}: home bucket {simple_hash(name, size)}, stored in {i} after {probes} probe(s)")
print(slots)
Ada: home bucket 3, stored in 3 after 1 probe(s)
Bob: home bucket 2, stored in 2 after 1 probe(s)
Eve: home bucket 1, stored in 1 after 1 probe(s)
Zoe: home bucket 1, stored in 4 after 4 probe(s)
Lea: home bucket 1, stored in 5 after 5 probe(s)
[None, 'Eve', 'Bob', 'Ada', 'Zoe', 'Lea', None]

Open addressing avoids lists and pointers, which is cache-friendly (Python's own dict uses a form of it), but deleting needs care: you can't simply empty a slot, or later probe chains break, so deleted slots are marked with a "tombstone".

Summary

Operation Average Worst (all keys collide)
Insert O(1) O(n)
Lookup O(1) O(n)
Delete O(1) O(n)

Hash tables don't keep keys in any useful order; if you need sorted order or range queries, use a sorted array or a balanced search tree. The next two lessons use the two classic flavours: hash sets (keys only) and hash maps (key → value).

Test yourself

What does the hash function of a hash table decide?

  1. The sort order of the keys
  2. Which bucket a key is stored in
  3. How many buckets there are
  4. Whether the key is a string

With the lesson's hash (sum of character codes mod 7), why do "Eve" and "Zoe" collide?

  1. They have the same length
  2. Their code sums (288 and 302) leave the same remainder 1 when divided by 7
  3. They start with a capital letter
  4. They don't collide

What keeps hash-table operations O(1) on average as more keys are added?

  1. Sorting each bucket
  2. Growing the table to keep the load factor low
  3. Using longer keys
  4. Removing old keys automatically