Sub topic 12
Where Hash Tables Are Used
This chapter assumes you can read Python, know how a hash table finds a key (hash, bucket index, collision handling), and know why lookups are O(1) on average. It covers the jobs hash tables do in real programs, the key rules each job depends on, and the cases where a hash table is the wrong choice.
The common thread
Almost every use of a hash table is one of three questions asked about a key:
- Have I seen this key before?
- What value is attached to this key?
- What should I do with all the items that share this key?
A hash table answers each in O(1) on average, without scanning the data. Once you can phrase a problem as "look something up by an exact key," a hash table is usually the first tool to try.
Sets: membership and deduplication
A set is a hash table that stores keys and no values. Its main operation is x in s. With a list, that test scans every element and costs O(n). With a set, it costs O(1) on average.
Removing duplicates while keeping the first-seen order combines a set for the "seen" test with a list for the output:
def dedupe(items):
seen = set()
result = []
for item in items:
if item not in seen:
seen.add(item)
result.append(item)
return result
words = ["apple", "pear", "apple", "fig", "pear", "apple"]
print(dedupe(words))This prints ['apple', 'pear', 'fig']. Calling set(words) would also remove duplicates, but it gives no ordering guarantee you should rely on in a general design. The explicit seen set keeps the order.
Typical uses of this pattern:
- Checking whether a user ID is on a blocklist.
- Detecting cycles in a graph traversal by tracking visited nodes.
- Finding duplicate records in a file.
- Computing the intersection or difference of two collections.
Counting: frequency maps
A counting map stores an integer per key. Each new occurrence reads the old count, adds one, and writes it back. Both steps are O(1) on average, so counting n items costs O(n) in total.
from collections import Counter
words = ["apple", "pear", "apple", "fig", "pear", "apple"]
counts = {}
for w in words:
counts[w] = counts.get(w, 0) + 1
print(counts)
print(Counter(words).most_common(1))The output is {'apple': 3, 'pear': 2, 'fig': 1} followed by [('apple', 3)]. Counter is a dictionary subclass that wraps this loop.
Counting is the base of many tasks: word frequencies, histograms, finding the majority element, and checking whether two strings are anagrams by comparing their letter counts.
Grouping and indexing
When the value for a key is a list, a hash table becomes a grouping structure. The key is a property shared by the items, and the value collects every item with that property.
from collections import defaultdict
def group_anagrams(words):
groups = defaultdict(list)
for w in words:
groups["".join(sorted(w))].append(w)
return list(groups.values())
print(group_anagrams(["listen", "silent", "enlist", "google", "gogole", "cat"]))This prints [['listen', 'silent', 'enlist'], ['google', 'gogole'], ['cat']]. Anagrams sort to the same string, so that string works as a canonical key.
An inverted index in a search engine uses the same shape. The keys are words and the values are lists of documents that contain them. Database hash indexes and join algorithms also use it. A hash join builds a table on one input keyed by the join column, then probes it with each row of the other input.
Complement lookup
Some problems seem to need a nested loop but reduce to a single pass when you store what you have already seen. The classic case is finding two numbers that sum to a target:
def two_sum(nums, target):
index_of = {}
for i, n in enumerate(nums):
j = index_of.get(target - n)
if j is not None:
return j, i
index_of[n] = i
return None
print(two_sum([2, 7, 11, 15], 9))This prints (0, 1). A nested loop costs O(n²). This version does one O(1) average lookup per element, so it costs O(n) on average. It trades memory for time, which is the usual bargain with hash tables.
Caching and memoization
A cache maps the inputs of an expensive computation to its result. When the same inputs come again, you return the stored result. Memoization is the name for this applied to function calls.
def memoize(fn):
cache = {}
def wrapper(*args):
if args not in cache:
cache[args] = fn(*args)
return cache[args]
return wrapper
@memoize
def fib(n):
return n if n < 2 else fib(n - 1) + fib(n - 2)
print(fib(80))This prints 23416728348467685. Without the cache, the naive recursion makes an exponential number of calls. With it, each value of n is computed once.
The cache key here is the tuple args. That works only when every argument is hashable. Calling fib with a list would raise TypeError: unhashable type: 'list'. The standard library's functools.cache has the same restriction.
An unbounded cache grows forever. Production caches usually have a capacity limit and an eviction policy. A least-recently-used (LRU) cache combines a hash table, for O(1) lookup, with an ordering of keys by recency, for O(1) eviction. Python's OrderedDict provides both:
from collections import OrderedDict
class LRUCache:
def __init__(self, capacity):
self._data = OrderedDict()
self._capacity = capacity
def get(self, key, default=None):
if key not in self._data:
return default
self._data.move_to_end(key)
return self._data[key]
def put(self, key, value):
self._data[key] = value
self._data.move_to_end(key)
if len(self._data) > self._capacity:
self._data.popitem(last=False)
cache = LRUCache(2)
cache.put("a", 1)
cache.put("b", 2)
cache.get("a")
cache.put("c", 3)
print(cache.get("b"), cache.get("a"))This prints None 1. Reading "a" marked it as recent, so adding "c" evicted "b".
What each use requires from the key
| Use | Stores | Key requirement |
|---|---|---|
| Set, deduplication | Keys only | Hashable, with equality that matches your idea of "same" |
| Counting | Integer per key | Same as above |
| Grouping | List per key | The key must be computed the same way for every item |
| Cache | Result per key | All inputs hashable, and the function must be pure |
The last row has a trap. A cache returns the stored result for equal inputs, so it is only correct if the function gives the same output every time for the same input. Caching a function that reads the clock, a file, or a database returns stale answers.
Common errors
- Mutating a key after insertion. If an object's hash depends on fields you later change, the table looks in the wrong bucket and the entry becomes unreachable. Use immutable keys such as strings, integers, tuples, and frozen dataclasses.
- Using a list as a membership structure in a loop.
if x in some_listinside a loop over n items is O(n²). Convertsome_listto a set once before the loop. - Relying on iteration order of a set. Dictionaries in Python preserve insertion order, but sets do not guarantee any order. Other languages make different promises, or none.
- Mixing numeric types as keys. In Python,
1,1.0, andTrueare equal and hash alike, so they share one entry.float("nan")is not equal to itself, so a NaN key can be inserted but not found by value. - Assuming O(1) is a hard bound. It is an average. A single insert that triggers a resize costs O(n), and adversarial keys can degrade lookups to O(n).
Where hash tables fit poorly
A hash table scatters keys on purpose, so it cannot answer questions that depend on key order.
| Need | Better choice |
|---|---|
| Smallest or largest key | Heap or balanced search tree |
| All keys in a range | Balanced search tree or sorted array |
| Next key after x | Balanced search tree |
| Strict worst-case latency per operation | Balanced search tree, or a table presized to avoid resizes |
| Very small collections (a handful of items) | A plain list or array, which is often faster due to lower overhead |
Memory is another cost. A table keeps spare capacity so the load factor stays low, so it uses more space than a packed array of the same items.
Exercise
You have a log of one million request IDs, and you must report every ID that appears more than once, in the order of its second appearance. Describe a single-pass approach, give its average time complexity, and say what data structures you use.
Show answer
Keep two sets, seen and reported, and an output list. For each ID in order: if it is not in seen, add it to seen. Otherwise, if it is not in reported, add it to reported and append it to the output list. Each set operation is O(1) on average, so the whole pass is O(n) on average, using O(n) extra memory. The output order is the order of each ID's second appearance because the ID is appended at the moment the duplicate is detected.
Exercise
A teammate memoizes a function price(item, region) with a dictionary keyed by (item, region). Later, item becomes a mutable dict holding product attributes. What happens, and how would you fix it?
Show answer
Building the key (item, region) raises TypeError: unhashable type: 'dict', because a tuple is only hashable if all its elements are. Fix it by keying on an immutable identifier such as the product ID, or by converting the attributes to an immutable form such as a frozen dataclass or a tuple of sorted items. Also confirm that price is a pure function, or the cache may return stale values.