Skip to content
LeetQuant
QD01 Data Structures and Algorithms

QD01 · Data Structures and Algorithms · Lesson 3 of 7

Hash Maps and Sets

How hash tables work inside, collisions, load factor and resizing, why O(1) is an average and not a guarantee, and the hash-map patterns behind most screening questions.

16 min

Objective

Explain what happens inside dict and set well enough to justify "O(1)O(1) 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 mm buckets plus a hash function hh. To store key kk, compute h(k)h(k) and use slot h(k) mod mh(k) \bmod m. If hh spreads keys evenly, each bucket holds about n/mn/m keys, so a lookup inspects a constant number of entries no matter how large nn 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), because 1 == 1.0 == True. They are therefore the same key.

Collisions

Two keys collide when they land in the same slot. With nn keys hashed uniformly into mm slots, each of the (n2)\binom{n}{2} pairs collides with probability 1/m1/m, so

E[colliding pairs]=n(n−1)2m.\mathbb{E}[\text{colliding pairs}] = \frac{n(n-1)}{2m} .

This is the birthday problem: collisions appear once nn is around m\sqrt{m}, long before the table is full. There are two ways to handle them.

  • Separate chaining: each bucket holds a small list. With load factor α=n/m\alpha = n/m, an unsuccessful search scans a chain of expected length α\alpha and a successful one inspects about 1+α/21 + \alpha/2 entries. Java's HashMap and C++'s std::unordered_map work 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 12(1+11−α)\frac12\big(1 + \frac{1}{1-\alpha}\big) probes for a hit and 12(1+1(1−α)2)\frac12\big(1 + \frac{1}{(1-\alpha)^2}\big) for a miss. CPython's dict and set use open addressing with a pseudo-random probe sequence.
Load factor α\alphaChaining, hitLinear probing, hitLinear probing, miss
0.51.251.52.5
2/31.332.05.0
0.91.455.550.5

Open addressing degrades sharply as α→1\alpha \to 1, which is why such tables resize early: CPython grows a dict once it is about two-thirds full.

Resizing and amortised cost

When α\alpha passes a threshold, the table allocates an array a constant factor larger and rehashes every key into it. That single insert costs O(n)O(n), but it happens rarely. With doubling, the rehashes up to size nn copy at most n+n/2+n/4+⋯<2nn + n/2 + n/4 + \dots < 2n keys in total, so the cost per insert is O(1)O(1) 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

"O(1)O(1)" for a hash table is an expected cost, under the assumption that the hash spreads keys well. The worst case is O(n)O(n) per operation, when every key lands in one chain or one probe cluster, which makes a loop of nn inserts O(n2)O(n^2).

  • 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: O(log⁡n)O(\log n) worst case for everything.

Worked example

how full is a full-looking table?

You hash n=1000n = 1000 order ids uniformly into m=1024m = 1024 buckets with separate chaining. How many colliding pairs do you expect, and what fraction of buckets do you expect to be empty?

Show solution

Colliding pairs. Each of the (10002)=499,500\binom{1000}{2} = 499{,}500 pairs shares a bucket with probability 1/10241/1024:

1000×9992×1024≈487.8.\frac{1000 \times 999}{2 \times 1024} \approx 487.8 .

Empty buckets. A given bucket is missed by every key with probability (1−1/m)n=(1023/1024)1000≈e−1000/1024≈0.376(1 - 1/m)^n = (1023/1024)^{1000} \approx e^{-1000/1024} \approx 0.376. So about 37.6% of the buckets, roughly 385 of them, are empty, even though α≈0.98\alpha \approx 0.98.

The lesson: uniform hashing is not uniform occupancy. The average chain length is α\alpha, but chains of 3 or 4 are common, and the probability of no collision at all is essentially zero once n≫mn \gg \sqrt{m}. Expected O(1)O(1) still holds because the average work per lookup is 1+α/21 + \alpha/2.

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, O(n)O(n) time and space, against O(n2)O(n^2) for all pairs or O(nlog⁡n)O(n \log n) 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 kk?": window (i,j](i, j] sums to kk exactly when Pj−Pi=kP_j - P_i = k, so count earlier prefix sums equal to Pj−kP_j - k.

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 O(n)O(n) 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 O(n)O(n) 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 O(n)O(n) method.

Show solution

A stretch from day ii to day j−1j - 1 nets to zero exactly when the prefix sums agree, Pi=PjP_i = P_j. 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 0,3,2,0,4,0,2,00, 3, 2, 0, 4, 0, 2, 0. The value 0 occurs 4 times, giving (42)=6\binom{4}{2} = 6 windows, and the value 2 occurs twice, giving 1 more: 77 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 h(k) mod mh(k) \bmod m; lookups are O(1)O(1) expected when the hash spreads keys and the load factor α=n/m\alpha = n/m is bounded.
  • Collisions start around n≈mn \approx \sqrt{m}; chaining costs about 1+α/21 + \alpha/2 per hit, linear probing blows up as α→1\alpha \to 1, so tables resize early and cost O(1)O(1) amortised per insert.
  • The worst case is O(n)O(n) 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.0 and True are 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).