Sub topic 1
Hash Tables: How Key-Value Lookup Works in Constant Average Time
Prerequisites
This chapter assumes basic programming, arrays or lists, loops, functions, integer modulo, and introductory Big-O notation.
What a Key-Value Mapping Needs to Do
A key-value mapping stores a value under a key. A key is an identifier, such as "user42" or "email". A value is the data associated with that identifier.
A mapping must support these operations:
- Put: store or replace a value for a key.
- Get: find the value for a key.
- Remove: delete a key and its value.
- Membership test: determine whether a key exists.
The key property is direct access. The caller should not need to scan every stored pair.
| Operation | Example | Desired average cost |
|---|---|---|
| Put | `scores["Ada"] = 95` | O(1) |
| Get | `scores["Ada"]` | O(1) |
| Remove | `del scores["Ada"]` | O(1) |
Why Arrays Are Fast and What They Lack
An array stores elements in consecutive positions. If you know an integer index, the array can calculate the element’s address directly. Reading items[5] therefore takes O(1) time.
Arrays do not naturally accept arbitrary keys. To find "Ada" in an array of key-value pairs, you might scan from the beginning. That takes O(n) time in the worst case.
A hash table combines an array with a calculation that converts a key into an index.
names = ["Ada", "Lin", "Mo"]
print(names[1]) # LinHash Functions: Turning Keys into Integers
A hash function maps a key to an integer called a hash value. A useful hash function is deterministic: equal keys produce equal hash values. It should also spread different keys across many values.
def string_hash(s, size):
h = 0
for ch in s:
h = (h * 31 + ord(ch)) % size
return h
print(string_hash("apple", 8))This example reduces the result during calculation, but hash tables commonly apply the table size afterward.
From Hash Value to Bucket Index
For an array with m buckets, the table computes:
index = hash(key) % m
The modulo operator produces a number from 0 through m - 1, so the result is a valid array index.
Exercise
A table has 8 buckets, and a key's hash value is 37. What bucket index does it use?
Show answer
37 % 8 is 5, so the key maps to bucket 5.