Sub topic 12
Where Hash Tables Are Used
Prerequisites
This chapter assumes you know how a hash table turns a key into a bucket index, how collisions are resolved, and why average lookup is O(1). The examples use Python.
One structure, many jobs
Most uses of a hash table rely on one property. Given a key, you can reach its entry in constant average time without scanning the other entries. Sets, counters, caches, and deduplication are the same table with different choices of key and value.
| Use | Key | Value |
|---|---|---|
| Set | The element | None, or a placeholder |
| Counting | The item being counted | The running count |
| Cache | The function input | The computed result |
| Deduplication | The item or its identifier | None, because only presence matters |
Sets and membership
A set is a hash table that stores only keys. The test x in s hashes x, jumps to one bucket, and compares keys there. The same test on a list compares x with each element, which costs O(n).
Counting
Counting is a table from item to integer. Each update is one lookup and one write.
from collections import Counter
words = "the cat and the hat and the bat".split()
counts = {}
for w in words:
counts[w] = counts.get(w, 0) + 1
print(counts)
print(Counter(words).most_common(1))The loop makes one pass over the data, so the total cost is O(n) on average. Sorting the words first would cost O(n log n).
Deduplication
Keep a set of items you have already seen. Checking and adding are both O(1) on average, so the whole pass is O(n).
def unique(items):
seen = set()
result = []
for item in items:
if item not in seen:
seen.add(item)
result.append(item)
return result
print(unique([3, 1, 3, 2, 1]))This version keeps the first occurrence of each item in its original order. Writing list(set(items)) is shorter, but it does not promise any order.
Caching
A cache maps the input of a computation to its result. If the key is already present, you skip the work. This is called memoization.
cache = {}
def fib(n):
if n < 2:
return n
if n in cache:
return cache[n]
cache[n] = fib(n - 1) + fib(n - 2)
return cache[n]
print(fib(80))Without the cache, fib(80) makes an astronomical number of repeated calls. With it, each value is computed once.
Limits to remember
- Keys must be hashable and must not change while stored. A key whose hash changes cannot be found again.
- A hash table does not sort its keys. Python dictionaries remember insertion order, but they cannot answer "the smallest key" or "all keys between a and b" efficiently.
- The table uses extra memory. The spare buckets that keep the load factor low are the cost of fast lookup.
Exercise
Exercise
You have a list of 1,000,000 user IDs and must check 10,000 incoming IDs against it. Why is it better to convert the list to a set first?
Show answer
Checking one ID against a list costs O(n), so 10,000 checks cost about 10,000 × 1,000,000 comparisons in the worst case. Building the set costs O(n) once, and each check then costs O(1) on average. The total is roughly 1,000,000 + 10,000 operations.