Objective
Explain what happens inside dict and set well enough to justify " on average", say when that fails, and recognise the four hash-map patterns that solve most array questions in one pass: complement lookup, frequency counting, a sliding window with a count map, and deduplication.
The idea
A hash table is an array of buckets plus a hash function . To store key , compute and use slot . If spreads keys evenly, each bucket holds about keys, so a lookup inspects a constant number of entries no matter how large is. Everything else (collisions, resizing, the worst case) is about what happens when keys do not spread perfectly.
Two rules follow straight from the design:
- Keys must be hashable and must not change. If a key's hash changes after insertion, it sits in the wrong bucket and can no longer be found. That is why Python refuses lists as keys and accepts tuples of immutable values.
- Equal keys must hash equally. Python guarantees
hash(1) == hash(1.0) == hash(True), because1 == 1.0 == True. They are therefore the same key.
Collisions
Two keys collide when they land in the same slot. With keys hashed uniformly into slots, each of the pairs collides with probability , so
This is the birthday problem: collisions appear once is around , long before the table is full. There are two ways to handle them.
- Separate chaining: each bucket holds a small list. With load factor , an unsuccessful search scans a chain of expected length and a successful one inspects about entries. Java's
HashMapand C++'sstd::unordered_mapwork this way. - Open addressing: every entry lives in the array itself, and a collision probes further slots in a fixed sequence until it finds a free one. With linear probing, Knuth's estimates are about probes for a hit and for a miss. CPython's
dictandsetuse open addressing with a pseudo-random probe sequence.
| Load factor | Chaining, hit | Linear probing, hit | Linear probing, miss |
|---|---|---|---|
| 0.5 | 1.25 | 1.5 | 2.5 |
| 2/3 | 1.33 | 2.0 | 5.0 |
| 0.9 | 1.45 | 5.5 | 50.5 |
Open addressing degrades sharply as , which is why such tables resize early: CPython grows a dict once it is about two-thirds full.
Resizing and amortised cost
When passes a threshold, the table allocates an array a constant factor larger and rehashes every key into it. That single insert costs , but it happens rarely. With doubling, the rehashes up to size copy at most keys in total, so the cost per insert is amortised, the same argument as for list.append. (A simulation that doubles at two-thirds full copies about 1.4 keys per insert.) Latency-sensitive code avoids the occasional spike by sizing the table up front, e.g. reserve in C++.
Expected versus worst case
"" for a hash table is an expected cost, under the assumption that the hash spreads keys well. The worst case is per operation, when every key lands in one chain or one probe cluster, which makes a loop of inserts .
- Adversarial keys. If an attacker can choose keys and knows the hash function, they can force collisions (hash flooding). Python randomises string and bytes hashes per process for this reason (
PYTHONHASHSEED). - Structured keys. Python's integer hash is essentially the identity (
hash(12345) == 12345), so integer keys that share a large power-of-two stride are a known weak spot for simple tables that take the low bits. A good table mixes the bits before taking the slot. - Bad custom hashes. A class whose
__hash__returns a constant is correct but turns every dictionary of it into a linked list.
When you need a guaranteed bound or ordered iteration, use a balanced search tree instead: worst case for everything.
Worked example
how full is a full-looking table?
You hash order ids uniformly into buckets with separate chaining. How many colliding pairs do you expect, and what fraction of buckets do you expect to be empty?
Show solutionHide solution
Colliding pairs. Each of the pairs shares a bucket with probability :
Empty buckets. A given bucket is missed by every key with probability . So about 37.6% of the buckets, roughly 385 of them, are empty, even though .
The lesson: uniform hashing is not uniform occupancy. The average chain length is , but chains of 3 or 4 are common, and the probability of no collision at all is essentially zero once . Expected still holds because the average work per lookup is .
Pattern 1: complement lookup (two-sum)
To find two positions whose values sum to a target, store each value's index as you scan and ask whether the complement has been seen. One pass, time and space, against for all pairs or for sort-and-two-pointers (which also loses the original indices).
def two_sum(xs, target):
where = {} # value -> index of an earlier occurrence
for j, x in enumerate(xs):
i = where.get(target - x)
if i is not None:
return i, j
where[x] = j # insert after the lookup: no self-pairing
return None
print(two_sum([3, 8, 11, 5, 2], 13)) # (1, 3)
The same idea with prefix sums answers "how many windows sum to ?": window sums to exactly when , so count earlier prefix sums equal to .
Pattern 2: frequency counting
A Counter (or defaultdict(int)) turns "group", "most common", "is this an anagram" and "distribution of outcomes" into one pass. Distributions are a quant favourite: the exact distribution of a dice sum is a dictionary from total to count, updated one die at a time.
Pattern 3: sliding window with a count map
For "longest window satisfying a condition on its contents", move a right pointer forward, update counts, and advance a left pointer while the window is invalid. Each index enters and leaves once, so the scan is even with the inner while.
def longest_k_distinct(xs, k):
count, left, best = {}, 0, 0
for right, x in enumerate(xs):
count[x] = count.get(x, 0) + 1
while len(count) > k: # too many distinct: shrink from the left
y = xs[left]
count[y] -= 1
if count[y] == 0:
del count[y] # keep len(count) = number of distinct
left += 1
best = max(best, right - left + 1)
return best
syms = ["AAPL", "MSFT", "AAPL", "TSLA", "TSLA", "AAPL", "NVDA", "TSLA"]
print(longest_k_distinct(syms, 2)) # 4
The answer 4 is the stretch AAPL, TSLA, TSLA, AAPL. Forgetting the del is the classic bug: zero counts would still count as distinct symbols.
Pattern 4: deduplication
set(xs) removes duplicates in but forgets order. list(dict.fromkeys(xs)) keeps first-seen order, because dicts preserve insertion order (guaranteed since Python 3.7): [105, 101, 105, 103, 101, 107] becomes [105, 101, 103, 107]. For a stream too large to hold, say so and discuss approximate structures (a Bloom filter answers "seen before?" with no false negatives and a tunable false-positive rate).
Worked example
zero-PnL windows
A strategy's daily PnL is [3, -1, -2, 4, -4, 2, -2]. How many contiguous stretches of days net to exactly zero? Give an method.
Show solutionHide solution
A stretch from day to day nets to zero exactly when the prefix sums agree, . So count, for each prefix sum, how many earlier prefixes had the same value.
from collections import defaultdict
def count_zero_sum(pnl):
seen = defaultdict(int)
seen[0] = 1 # the empty prefix
s = total = 0
for x in pnl:
s += x
total += seen[s] # each earlier equal prefix closes a window
seen[s] += 1
return total
print(count_zero_sum([3, -1, -2, 4, -4, 2, -2])) # 7
Check by hand. The prefix sums are . The value 0 occurs 4 times, giving windows, and the value 2 occurs twice, giving 1 more: in total. A brute force over all 28 windows agrees. Seeding seen[0] = 1 is what counts windows that start on day one, such as [3, -1, -2].
Knowledge check
In Python, d = {1: 'a'}; d[1.0] = 'b'; d[True] = 'c'. What is d?
Knowledge check
A hash table doubles its capacity whenever it becomes two-thirds full. What is the cost of inserting n keys, starting from an empty table?
Knowledge check
Your sliding-window solution keeps a dict of counts and advances the left pointer inside a while loop. Why is it still O(n) rather than O(n²)?
Key takeaways
- A hash table maps keys to buckets with ; lookups are expected when the hash spreads keys and the load factor is bounded.
- Collisions start around ; chaining costs about per hit, linear probing blows up as , so tables resize early and cost amortised per insert.
- The worst case is per operation (adversarial or structured keys, bad
__hash__); use a balanced tree when you need guarantees or order. - Keys must be immutable and equal keys hash equally (
1,1.0andTrueare one key). - Four patterns: complement lookup, frequency counts, sliding window with a count map, order-preserving dedup with
dict.fromkeys.
Practice problems
Finished reading?
Answer the 3 knowledge checks to complete this lesson (0 done).