Arrays & Hashing — jump straight to the answer
Contiguous memory and O(1) indexing, dynamic arrays and amortized growth, hash functions, collisions, load factor, Python’s list, dict and set — and the hashing patterns behind a huge share of interview problems.
AChapter introduction
Prerequisites
You should be comfortable with Python variables, loops, functions, lists and dictionaries at the “I have used them” level, and with Big-O notation (O(1), O(n), O(n²)). If Big-O is new, read Chapter 01 · Time & Space Complexity first. No mathematics beyond the remainder operator % and simple fractions is needed.
Learning objectives
After completing this chapter you will be able to:
- Explain why an array element can be read in O(1) time using the address formula, and why inserting in the middle costs O(n).
- Explain how a dynamic array (Python’s
list) grows, and prove that appending is amortized O(1). - Describe a hash table: hash function, buckets, collisions, separate chaining, open addressing and load factor.
- State when hash operations are O(1) on average and why their worst case is O(n).
- Implement a dynamic array and a hash map from scratch in Python, and know the built-in equivalents.
- Recognise and apply the core hashing patterns: seen-set, complement lookup, frequency count, canonical-key grouping and prefix-sum + hash map.
BFundamental understanding
What is an array?
An array is a fixed number of equally sized slots laid out next to each other in memory. Because the slots are contiguous and the same size, the machine can compute where slot i lives with one multiplication and one addition, instead of walking there. MIT’s 6.006 describes this as the array’s defining strength: reading or writing any position is constant time in the word-RAM model. [1]
What is hashing?
Arrays are fast only when you already know the position. Very often we know a key instead — a username, a word, a product ID — and want its associated value. A hash table fixes this by using a hash function to turn the key into a number, then using that number (modulo the table size) as an array index. [2][3]
Why do these concepts exist?
Both structures exist to avoid searching. Without an array, finding the 500th item means walking past 499 others (as in a linked list). Without hashing, checking “have I seen this value?” means comparing against everything stored so far — O(n) per question and O(n²) for a whole list. Hashing converts those comparisons into a computed jump, which is why Python uses hash tables for dict and set and even for most namespaces. [5][18]
A little history
Hashing is older than most programming languages. In January 1953, Hans Peter Luhn wrote an internal IBM memorandum that used hashing with chaining. [12] Linear probing, the simplest form of open addressing, was first analysed by Donald Knuth in 1963. [13] Later milestones in the Advanced section — Bloom filters (1970), consistent hashing (1997) and cuckoo hashing (2001) — all build on the same idea. [15][16][14]
Fundamental principles
- Position is computed, not searched. Array index → address by arithmetic; key → index by hashing. [1][2]
- Contiguity has a price. Keeping elements packed means inserting or deleting in the middle must shift everything after it. [1]
- Growth is paid in rare, big installments. A dynamic array (and a hash table) occasionally copies everything into a bigger block; spread over many cheap operations, the cost per operation stays constant on average. [1][2]
- Equal keys must hash equally. The only hard rule for a hash function is that objects which compare equal produce the same hash; everything else is about speed. [7]
CThe problem statement
The dictionary (lookup) problem
| Component | Specification |
|---|---|
| Data | A changing collection of n items, each identified by a key (a number, string, tuple …). |
| Operations | insert(k, v), find(k), delete(k) — the “dynamic set” or dictionary interface. [2] |
| Output | find(k) returns the stored value or reports that k is absent. |
| Goal | Make every operation as close to constant time as possible, even when n is in the millions. |
Why the naive approach is inefficient
Store pairs in an unsorted list and scan for the key: each find costs O(n), and Python’s x in list is exactly such a linear scan. [6] Doing that once per element of an input — the classic “find duplicates” loop — costs O(n²); for n = 105 that is about 5·109 comparisons.
Limitations of alternative approaches
Keeping the list sorted allows binary search in O(log n), but every insertion must shift elements to keep the order, costing O(n). [1] A balanced binary search tree gives O(log n) for everything and keeps keys ordered, which is valuable — but if you never need order, you are paying log n for nothing. Direct addressing (an array indexed by the key itself) is O(1) but only works when keys are small integers; a table indexed by every possible 64-bit ID would be absurdly large. [2]
How hashing improves the solution
Hashing keeps the O(1) jump of direct addressing but compresses the huge key space into a table of size m = Θ(n). With a good (randomly chosen) hash function and the table kept proportional to n, MIT 6.006 shows that the expected chain length is 1 + (n−1)/m = O(1), so insert, find and delete take expected amortized O(1) time. [2]
DVisual whiteboard explanations
All diagrams in this chapter use one colour language:
- Six 8-byte slots start at base address
1000(illustrative numbers). - To read
A[4], compute1000 + 4 × 8 = 1032and fetch that address directly. - The cost is the same for
A[0]orA[1 000 000]: one multiply, one add, one memory read.
list holds a reference to an object, which is why a list can mix types while still indexing in constant time. [4]
- Insert 15 at index 1: elements 20, 30, 40, 50 each move one slot right (4 moves), then 15 is written.
- Delete index 0 (the 10): everything after it moves one slot left to close the gap.
- Appending at the end moves nothing.
list.insert and list.pop(i) as O(n − i) for this reason. [6]
- Toy hash: add the character codes, then take
mod 8."cat"→ 99+97+116 = 312 → 312 mod 8 = 0. "act"has the same letters, so the same sum: it also lands in bucket 0 — a collision. Bucket 0 now holds a chain of two entries."dog"(314 → 2) and"fish"(426 → 2) collide in bucket 2;"bird"→ 1 and"ant"→ 3 have buckets to themselves.
- Same six keys, same toy hash, but every key must live in the 8-slot array. Insert in order: cat, bird, act, dog, fish, ant.
- cat → 0 and bird → 1 land at home. act wants 0 (taken), tries 1 (taken), lands in 2. dog wants 2 (now taken) → 3. fish wants 2 → 3 → 4. ant wants 3 → 4 → 5.
- Slots 0–5 now form one solid run — a primary cluster. Any key hashing into it must walk to its end.
- Capacity starts at 1. Each time the block is full, allocate one twice as large and copy everything across.
- Appending 9 items triggers copies of 1, 2, 4 and 8 elements — 15 copies in total, fewer than 2 × 9.
- In general the copies form 1 + 2 + 4 + … < 2n, so n appends cost O(n) in total.
EInteractive lab
All labs below work. Change the inputs, step forwards and backwards, and watch the state panel explain each step.
FInternal working
F.1 Static arrays in memory
A static array is one allocation of n · s bytes. Reading A[i] executes three steps: (1) multiply i by the element size s; (2) add the base address; (3) load the word at that address. None of the steps depends on n. [1] Because neighbouring elements share cache lines, scanning an array front to back is also very fast in practice.
F.2 Python’s list is a dynamic array of references
CPython implements lists as variable-length arrays, not linked lists: the list object holds a pointer to a contiguous array of references to the element objects, so indexing cost does not depend on the list’s size. [4] When the array runs out of room, CPython allocates extra space so that the next few appends need no reallocation. [4] Python’s documentation therefore lists append as amortized O(1), insert(i, x) and pop(i) as O(n − i), and x in list as O(n). [6]
F.3 Execution flow of a dynamic-array append
- If
size < capacity: write the value at indexsize, incrementsize. Done — O(1). - Otherwise allocate a new block of (say) twice the capacity.
- Copy all
sizeexisting elements into the new block — Θ(n). - Release the old block, then perform step 1.
F.4 Hash functions
A hash function must be deterministic (the same key always gives the same value), fast to compute, and should spread keys uniformly over the buckets. [3] Python’s rule is stricter about one thing only: objects that compare equal must have the same hash value. [7] That is also why mutable containers such as lists and dicts are not hashable — if a key’s contents changed, its hash would change and the table could no longer find it. [8][5]
The toy hash in the figures (sum of character codes) violates “spread uniformly”: every anagram collides. The usual fix for strings is a polynomial rolling hash, h(s) = s₀·pk−1 + s₁·pk−2 + … + sk−1 (mod M), which weights each position differently so that “cat” and “act” differ. [22] Lab 2 lets you switch between the two and see the collisions disappear.
F.5 From hash to bucket
The hash value is usually huge, so the table reduces it to an index with index = h(k) mod m. [2] Lookup then proceeds:
- Compute
h = hash(key)andi = h % m. - Chaining: scan the (short) list in bucket
i, comparing keys with==. - Linear probing: inspect slot
i; if it holds a different key, tryi+1,i+2, … (wrapping around) until the key or an empty slot is found. [3] - Return the value, or report “not found”.
F.6 Deletion and tombstones
With chaining, deletion just removes the entry from its bucket’s list. With open addressing you cannot simply empty the slot: a later search that probes through it would stop early and miss keys stored beyond it. Implementations therefore mark the slot as deleted (a “dummy” or tombstone) so searches continue past it; CPython’s dict source describes slots as Unused, Dummy or Active for exactly this reason. [11] Lab 2 shows tombstones as red ✕ slots.
F.7 Resizing
As keys are added, α = n/m rises and chains or clusters grow. The remedy is to allocate a bigger table (commonly double the size) and re-insert every key, because each key’s bucket depends on m. [12] The re-insert costs Θ(n), but like dynamic-array doubling it happens rarely enough to be amortized O(1) per operation. [2]
F.8 How CPython’s dict works
Python’s dictionaries are resizable hash tables that use hash() on each key. [5] They use open addressing rather than chaining: the source code describes a probe recurrence of the form j = ((5*j) + 1) mod 2**i, perturbed by higher bits of the hash so that all hash bits eventually influence the probe sequence. [11] Since Python 3.7, iteration order is guaranteed to be insertion order. [9] Since Python 3.4 the default string and bytes hash is SipHash, adopted to resist hash-collision denial-of-service attacks. [10]
F.9 Edge cases
| Situation | What happens |
|---|---|
| Index out of range | Python raises IndexError; a negative index counts from the end, which can silently hide bugs. |
| Empty array | len is 0; any index is invalid; pop() raises. |
| Unhashable key (list, dict, set) | TypeError: unhashable type. Use a tuple or frozenset instead. [8] |
| Duplicate key on insert | The value is overwritten; the size does not change. |
| Missing key | d[k] raises KeyError; use d.get(k, default) or defaultdict. |
| Changing a dict while iterating it | May raise RuntimeError or skip entries. [9] |
| All keys collide | Every operation degrades to O(n). [6] |
GMathematical foundation
G.1 The address formula
With b the base address and s the element size, the cost is constant regardless of i. [1]
G.2 Amortized cost of doubling (aggregate method)
Start with capacity 1 and double when full. Appending n elements triggers copies of sizes 1, 2, 4, …, 2k where 2k < n. Then
so n appends cost fewer than n + 2n = 3n element writes: amortized O(1) per append. [1] Our Python implementation in Section I reports exactly 1 023 copies for 1 000 appends, matching 210 − 1.
G.3 Load factor and expected chain length
Let n keys be stored in m buckets, α = n/m. If the hash function is chosen at random from a universal family (so any two distinct keys collide with probability at most 1/m), the expected size of the chain containing a given key is
and keeping m = Ω(n) makes α = O(1), so operations are expected O(1). MIT 6.006 gives the universal family hab(k) = ((ak + b) mod p) mod m for a prime p. [2]
G.4 Linear probing cost
Under the uniform hashing assumption, Princeton’s Algorithms gives the average number of probes for linear probing at load factor α as about
At α = 0.5 that is 1.5 and 2.5 probes; at α = 0.9 it is 5.5 and 50.5 — the cost explodes as the table fills, which is why open-addressing tables must keep α well below 1. [3]
- Curves are computed exactly from the formulas above for α from 0 to 0.95.
- Chaining degrades gently (a straight line); linear probing is cheap until about α ≈ 0.7, then shoots up.
G.5 Why the worst case is still O(n)
No fixed hash function can avoid collisions for every input: if the key universe is larger than m, some bucket receives many keys, and an adversary who knows h can choose exactly those keys. That is why MIT recommends choosing the hash function randomly from a family [2], why Python documents dict operations as O(n) in the worst case [6], and why Python adopted SipHash with a random key for strings. [10]
G.6 The birthday effect
Illustration Collisions arrive much earlier than intuition suggests. With m equally likely buckets, the probability that n keys are all distinct is ∏i<n(1 − i/m). For m = 365 this drops below ½ at n = 23 — the classic birthday paradox. Collisions are not a bug to eliminate; they are a certainty to handle.
HOperations & complexity analysis
H.1 Arrays (dynamic array, e.g. Python list)
| Operation | Best | Average | Worst | Aux. space |
|---|---|---|---|---|
Read / write A[i] | Θ(1) | Θ(1) | Θ(1) | O(1) |
| Append | Θ(1) | Θ(1) amortized | Θ(n) (resize) | O(1) amortized |
| Pop from end | Θ(1) | Θ(1) | Θ(1) | O(1) |
| Insert / delete at i | Θ(1) (at end) | Θ(n − i) | Θ(n) (at front) | O(1) |
Search x in A (unsorted) | Θ(1) | Θ(n) | Θ(n) | O(1) |
| Binary search (sorted) | Θ(1) | Θ(log n) | Θ(log n) | O(1) |
Slice A[a:b] | Θ(b − a) — creates a copy | O(b − a) | ||
Reasoning: indexing is the address formula; append is amortized by doubling (G.2); middle insert/delete shift n − i elements; unsorted search must look at every element in the worst case (it could be last or absent). Python’s documented costs match these rows. [1][6]
H.2 Hash tables (Python dict / set)
| Operation | Best | Average (expected) | Worst | Aux. space |
|---|---|---|---|---|
| Insert / update | Θ(1) | Θ(1) amortized | Θ(n) | O(1) amortized |
Lookup / k in d | Θ(1) | Θ(1) | Θ(n) | O(1) |
| Delete | Θ(1) | Θ(1) | Θ(n) | O(1) |
| Iterate all items | Θ(n) for Python dict; a plain chaining table also visits its m buckets: Θ(n + m) | O(1) | ||
| Build from n items | Θ(n) | Θ(n) | Θ(n²) | Θ(n) |
Assumptions: the averages assume a good hash function and a load factor kept bounded by resizing. [2] The worst case is when all keys collide. [6]
H.3 Time–space trade-off
Hashing spends memory to save time: a set of n items uses Θ(n) extra space (plus empty buckets kept free by the load-factor limit) to turn Θ(n) membership tests into expected Θ(1). Sorting the data in place instead costs Θ(n log n) time once and only O(1) extra space, with Θ(log n) lookups — the right choice when memory is tight or you also need order.
H.4 Theory vs Python reality
- Python does not expose array capacity, but
sys.getsizeofon a growing list reveals over-allocation: on CPython 3.11 (64-bit) the reported size changed only at lengths 1, 5, 9 and 17 while appending 20 items, so most appends needed no reallocation. [4] Exact numbers vary by version. list.pop(0)is O(n); usecollections.dequefor queues. [6]- Hashing a key is not free: computing the hash of a string is proportional to its length, so “O(1) lookup” really means O(1) hash-table work plus the cost of hashing and comparing the key.
IPython implementation
I.1 A dynamic array from scratch
class DynamicArray:
"""A growable array built on a fixed-size block, like CPython's list."""
def __init__(self):
self._capacity = 1
self._size = 0
self._data = [None] * self._capacity # the fixed-size block
self.copies = 0 # elements moved by resizes (for analysis)
def __len__(self):
return self._size
def _check(self, i):
if not 0 <= i < self._size:
raise IndexError(f"index {i} out of range for size {self._size}")
def __getitem__(self, i): # O(1): one address computation
self._check(i)
return self._data[i]
def __setitem__(self, i, value): # O(1)
self._check(i)
self._data[i] = value
def _resize(self, new_capacity): # O(n): copy every element
new_data = [None] * new_capacity
for k in range(self._size):
new_data[k] = self._data[k]
self.copies += self._size
self._data = new_data
self._capacity = new_capacity
def append(self, value): # amortized O(1)
if self._size == self._capacity:
self._resize(2 * self._capacity) # grow geometrically
self._data[self._size] = value
self._size += 1
def insert(self, i, value): # O(n - i): shift right
if not 0 <= i <= self._size:
raise IndexError(f"insert position {i} out of range")
if self._size == self._capacity:
self._resize(2 * self._capacity)
for k in range(self._size, i, -1):
self._data[k] = self._data[k - 1]
self._data[i] = value
self._size += 1
def pop(self, i=None): # O(n - i): shift left
if i is None:
i = self._size - 1
self._check(i)
value = self._data[i]
for k in range(i, self._size - 1):
self._data[k] = self._data[k + 1]
self._data[self._size - 1] = None
self._size -= 1
return value
def __repr__(self):
items = ", ".join(repr(self._data[k]) for k in range(self._size))
return f"DynamicArray([{items}], capacity={self._capacity})"
Line-by-line highlights
self._data = [None] * self._capacitysimulates one fixed-size memory block; we never callappendon it._checkrejects negative indices on purpose — unlike Python lists — so out-of-range bugs fail loudly.appenddoubles when full (2 * self._capacity): the geometric growth that gives amortized O(1).insertwalkskbackwards from the end so each element is moved before its slot is overwritten.popclears the vacated last slot (None) so the old reference does not keep an object alive.
Sample run (actual output)
arr = DynamicArray()
for x in [10, 20, 30, 40, 50]:
arr.append(x)
print(arr) # DynamicArray([10, 20, 30, 40, 50], capacity=8)
arr.insert(1, 15)
print(arr) # DynamicArray([10, 15, 20, 30, 40, 50], capacity=8)
print(arr.pop(0), arr) # 10 DynamicArray([15, 20, 30, 40, 50], capacity=8)
print(arr[2], len(arr)) # 30 5
arr[9] # IndexError: index 9 out of range for size 5
big = DynamicArray()
for x in range(1000):
big.append(x)
print(big.copies) # 1023 (= 1 + 2 + 4 + ... + 512 < 2 × 1000)
Dry run: insert(1, 15) on [10, 20, 30, 40, 50]
| Step | k | Action | _data[0..5] |
|---|---|---|---|
| start | — | size 5, capacity 8 — no resize | 10 20 30 40 50 _ |
| 1 | 5 | _data[5] = _data[4] | 10 20 30 40 50 50 |
| 2 | 4 | _data[4] = _data[3] | 10 20 30 40 40 50 |
| 3 | 3 | _data[3] = _data[2] | 10 20 30 30 40 50 |
| 4 | 2 | _data[2] = _data[1] | 10 20 20 30 40 50 |
| 5 | — | _data[1] = 15; size = 6 | 10 15 20 30 40 50 |
Four moves for n − i = 5 − 1 = 4, exactly as Θ(n − i) predicts.
I.2 A hash map with separate chaining
class HashMap:
"""Hash table with separate chaining and automatic resizing."""
def __init__(self, capacity=8, max_load=0.75):
self._buckets = [[] for _ in range(capacity)]
self._size = 0
self._max_load = max_load
def __len__(self):
return self._size
def _index(self, key):
return hash(key) % len(self._buckets) # hash -> bucket number
def put(self, key, value): # expected O(1)
bucket = self._buckets[self._index(key)]
for pair in bucket:
if pair[0] == key: # key already present: overwrite
pair[1] = value
return
bucket.append([key, value])
self._size += 1
if self._size / len(self._buckets) > self._max_load:
self._resize(2 * len(self._buckets))
def get(self, key, default=None): # expected O(1)
for k, v in self._buckets[self._index(key)]:
if k == key:
return v
return default
def __contains__(self, key):
sentinel = object()
return self.get(key, sentinel) is not sentinel
def remove(self, key): # expected O(1)
bucket = self._buckets[self._index(key)]
for pos, (k, _) in enumerate(bucket):
if k == key:
bucket.pop(pos)
self._size -= 1
return
raise KeyError(key)
def _resize(self, new_capacity): # O(n), rare
old = self._buckets
self._buckets = [[] for _ in range(new_capacity)]
for bucket in old:
for k, v in bucket:
self._buckets[self._index(k)].append([k, v])
def load_factor(self):
return self._size / len(self._buckets)
def capacity(self):
return len(self._buckets)
Line-by-line highlights
[[] for _ in range(capacity)]creates separate lists. Writing[[]] * capacitywould make every bucket the same list (Section L). [21]_indexuses Python’s built-inhash(), which already satisfies “equal keys → equal hashes”. [7]putcompares with==inside the bucket: equal hashes do not imply equal keys.__contains__uses a privatesentinelobject so that a stored value ofNonestill counts as present._resizerecomputes every index becausehash(k) % mchanges when m changes.
Sample run (actual output)
m = HashMap(capacity=4)
for k, v in [("apple", 3), ("banana", 5), ("cherry", 7), ("apple", 4)]:
m.put(k, v)
print(len(m), m.get("apple"), m.get("grape", 0), "banana" in m) # 3 4 0 True
print(m.capacity(), m.load_factor()) # 4 0.75
m.remove("banana")
print(len(m), "banana" in m) # 2 False
m.remove("banana") # KeyError: 'banana'
Note that the 4th put overwrote "apple" rather than adding a 4th entry, and that α = 3/4 = 0.75 did not exceed max_load, so no resize happened. Which bucket each word lands in varies between runs because Python randomises string hashes. [10]
I.3 Built-in Python alternatives
| Need | Use | Notes |
|---|---|---|
| Ordered sequence, index access | list | Dynamic array of references. [4] |
| Key → value | dict | Hash table; insertion-ordered since 3.7. [5][9] |
| Membership / de-duplication | set, frozenset | Hash table of keys only; frozenset is hashable. |
| Counting | collections.Counter | dict subclass for counting hashable objects; most_common(k). [19] |
| Grouping | collections.defaultdict(list) | Missing keys start as an empty list. |
| Queue (both ends) | collections.deque | O(1) at both ends, unlike list.pop(0). [6] |
| Typed numeric arrays | array.array, NumPy | Store raw numbers contiguously, not references. |
I.4 Comparing the implementations
Our classes are for understanding, not production: the built-ins are implemented in C, use open addressing with a tuned probe sequence (dict/set) and over-allocation heuristics (list), and are many times faster. [11][4] Asymptotically they match: our DynamicArray and list both give O(1) indexing and amortized O(1) append; our HashMap and dict both give expected O(1) operations with O(n) worst case.
JReal-world applications
| Area | How arrays / hashing are used |
|---|---|
| Programming languages | Python stores most namespaces — module globals, class attributes, instance attributes — as dictionaries, so every global-name lookup is a hash lookup. [18] |
| Databases | PostgreSQL offers hash indexes, which support only equality (=) lookups — exactly the trade-off of a hash table versus an ordered B-tree. [17] |
| Distributed systems | Consistent hashing assigns keys to servers so that resizing the cluster remaps only about n/m keys on average instead of nearly all of them. [16] |
| Web security | Because a predictable hash lets attackers force collisions and O(n) behaviour, Python switched string hashing to SipHash. [10] |
| Caches & backends | Illustration Session stores, memoisation (functools.lru_cache), rate limiters and de-duplication of events all reduce to “key → value in O(1)”. |
| Search & storage | Bloom filters (hash-based bit arrays) answer “definitely not present / maybe present” with no false negatives, letting systems skip expensive disk reads. [15] |
| Everything numeric | Illustration Images, audio buffers, matrices and network packets are arrays, because contiguous layout gives O(1) indexing and fast sequential scans. |
KComparison with alternatives
| Structure | Access by index | Find by key | Insert / delete | Keeps order? | Choose when… |
|---|---|---|---|---|---|
| Array / list | O(1) | O(n) | O(1) end, O(n) middle | Insertion order | You access by position or scan everything. |
| Sorted array | O(1) | O(log n) | O(n) | Sorted | Data is mostly static and you need ranges or order. |
| Linked list | O(n) | O(n) | O(1) at a known node | Insertion order | Frequent splicing at known positions. |
| Hash table | — | O(1) avg, O(n) worst | O(1) avg | No sorted order | Fast membership, counting, grouping by key. |
| Balanced BST | O(log n) (augmented) | O(log n) | O(log n) | Sorted | You need min/max, ranges, or predecessor/successor. |
Sources for the costs: MIT 6.006 compares array, linked-list and dynamic-array sequences [1] and hashing versus comparison-based sets [2].
LCommon mistakes & misconceptions
L.1 Hidden O(n) inside a loop
def has_dup(nums):
seen = []
for x in nums:
if x in seen: # O(n) scan
return True
seen.append(x)
return Falsedef has_dup(nums):
seen = set()
for x in nums:
if x in seen: # O(1) average
return True
seen.add(x)
return Falsex in list is O(n) but x in set is O(1) on average. [6]
L.2 Aliased rows with *
grid = [[0] * 3] * 2
grid[0][0] = 9
print(grid) # [[9, 0, 0], [9, 0, 0]]grid = [[0] * 3 for _ in range(2)]
grid[0][0] = 9
print(grid) # [[9, 0, 0], [0, 0, 0]]s * n does not copy the items; it references the same inner list multiple times. [21][20]
L.3 Unhashable keys
seen = {}
seen[[1, 2]] = "x"
# TypeError: unhashable type: 'list'seen = {}
seen[(1, 2)] = "x" # tuple is hashable
seen[frozenset({1, 2})] = "y"Lists and dicts are mutable and therefore not hashable. [8] Likewise, a class that defines __eq__ without __hash__ becomes unhashable, because Python sets its __hash__ to None. [7]
L.4 Mutating a dict while iterating it
for k in d:
if d[k] == 0:
del d[k]
# RuntimeError: dictionary changed
# size during iterationfor k in list(d): # iterate a copy
if d[k] == 0:
del d[k]
# or: d = {k: v for k, v in d.items() if v}Adding or deleting entries during iteration may raise RuntimeError or skip entries. [9]
L.5 Complexity misconceptions
- “Dict lookup is always O(1).” It is O(1) on average; the worst case is O(n). [6]
- “Append is O(1) every time.” It is amortized O(1); an individual append can be O(n). [1]
- “Slicing is free.”
A[a:b]copies b − a references. [6] - “Hashing a string is O(1).” Computing it is proportional to the string’s length.
list.pop(0)in a BFS loop silently makes it O(n²); usedeque.popleft().
L.6 Boundary errors and interview slips
- Off-by-one: valid indices are
0 … n−1;range(n)excludesn. - Two Sum: inserting the current number before checking lets an element pair with itself (e.g. target 6, nums [3]).
- Forgetting to state space: a hash-based O(n)-time solution usually uses O(n) extra space — say so.
- Using
d[k] += 1on a plain dict without initialising — useCounter,defaultdict(int)ord.get(k, 0) + 1.
MInterview preparation
M.1 The five hashing patterns
| Pattern | Idea | Typical problems |
|---|---|---|
| Seen-set | Remember what you have visited; check membership in O(1). | Contains Duplicate, Longest Consecutive Sequence |
| Complement lookup | For each x, ask whether the partner target − x was already seen. | Two Sum and variants |
| Frequency count | Count with Counter; compare or rank counts. | Valid Anagram, Top K Frequent |
| Canonical key | Map each item to a normal form; group by it. | Group Anagrams, Valid Sudoku |
| Prefix sum + hash map | Count earlier prefixes equal to running − k. | Subarray Sum Equals K — see Chapter 03 · Prefix Sum |
M.2 Common interview questions
- Why is array indexing O(1) but linked-list indexing O(n)?
- How does a dynamic array grow, and why is append amortized O(1)?
- What is a collision? Compare chaining and open addressing.
- What is the load factor and what happens when it gets too high?
- Why must dictionary keys be immutable/hashable?
- When would you choose a balanced BST over a hash table?
M.3 Coding exercises
1. Contains Duplicate EASY
LeetCode 217 — return true if any value appears at least twice.
Hint
Seen-set: stop as soon as you meet a value already in the set.Solution
def contains_duplicate(nums):
seen = set()
for x in nums:
if x in seen:
return True
seen.add(x)
return False
# contains_duplicate([1, 2, 3, 1]) -> True ; [1, 2, 3, 4] -> False
Time O(n) expected, space O(n). Alternative: sort and compare neighbours — O(n log n) time, O(1) extra space.
2. Valid Anagram EASY
LeetCode 242 — are two strings rearrangements of each other?
Hint
Two strings are anagrams exactly when their letter counts are equal.Solution
from collections import Counter
def is_anagram(s, t):
return len(s) == len(t) and Counter(s) == Counter(t)
Time O(n), space O(k) for k distinct characters.
3. Two Sum EASY
LeetCode 1 — indices of two numbers adding up to target.
Hint
Complement lookup: check fortarget − x before storing x. Lab 3 animates this.Solution
def two_sum(nums, target):
index_of = {} # value -> index
for i, x in enumerate(nums):
need = target - x
if need in index_of:
return [index_of[need], i]
index_of[x] = i
return []
# two_sum([2, 7, 11, 15], 9) -> [0, 1] ; two_sum([3, 2, 4], 6) -> [1, 2]
Time O(n) expected, space O(n). Brute force over all pairs is O(n²).
4. Group Anagrams MEDIUM
Hint
Canonical key: the sorted letters of a word are the same for all its anagrams. Lab 4 animates this.Solution
from collections import defaultdict
def group_anagrams(words):
groups = defaultdict(list)
for w in words:
groups["".join(sorted(w))].append(w) # canonical key
return list(groups.values())
# ["eat","tea","tan","ate","nat","bat"] -> [['eat','tea','ate'], ['tan','nat'], ['bat']]
Time O(n · k log k) for n words of length ≤ k. Using a 26-count tuple as the key makes it O(n · k).
5. Top K Frequent Elements MEDIUM
Hint
Count, then bucket by frequency: a frequency is between 1 and n, so an array of n + 1 buckets avoids sorting.Solution
from collections import Counter
def top_k_frequent(nums, k):
count = Counter(nums)
buckets = [[] for _ in range(len(nums) + 1)] # index = frequency
for x, c in count.items():
buckets[c].append(x)
out = []
for c in range(len(buckets) - 1, 0, -1):
for x in buckets[c]:
out.append(x)
if len(out) == k:
return out
return out
# top_k_frequent([1, 1, 1, 2, 2, 3], 2) -> [1, 2]
Time O(n), space O(n). Counter(nums).most_common(k) is the one-liner (O(n log k)). [19]
6. Product of Array Except Self MEDIUM
LeetCode 238 — without division.
Hint
Answer[i] = (product of everything left of i) × (product of everything right of i). Two passes.Solution
def product_except_self(nums):
n = len(nums)
out = [1] * n
left = 1
for i in range(n):
out[i] = left
left *= nums[i]
right = 1
for i in range(n - 1, -1, -1):
out[i] *= right
right *= nums[i]
return out
# product_except_self([1, 2, 3, 4]) -> [24, 12, 8, 6]
Time O(n), O(1) extra space besides the output. A pure array pattern — no hashing needed.
7. Longest Consecutive Sequence MEDIUM
LeetCode 128 — in O(n).
Hint
Put everything in a set. Only start counting from numbers x where x − 1 is not in the set.Solution
def longest_consecutive(nums):
s = set(nums)
best = 0
for x in s:
if x - 1 not in s: # x starts a run
length = 1
while x + length in s:
length += 1
best = max(best, length)
return best
# longest_consecutive([100, 4, 200, 1, 3, 2]) -> 4
Each number is visited by a while loop at most once across all starts, so the total is O(n) expected (amortized argument).
8. First Missing Positive HARD
LeetCode 41 — O(n) time and O(1) extra space.
Hint
Use the array itself as the hash table: value v belongs at index v − 1. Swap values into place.Solution
def first_missing_positive(nums):
n = len(nums)
for i in range(n):
while 1 <= nums[i] <= n and nums[nums[i] - 1] != nums[i]:
j = nums[i] - 1
nums[i], nums[j] = nums[j], nums[i]
for i in range(n):
if nums[i] != i + 1:
return i + 1
return n + 1
# first_missing_positive([3, 4, -1, 1]) -> 2 ; [7, 8, 9] -> 1
Each swap places one value permanently, so there are at most n swaps: O(n) time, O(1) extra space. This “index as hash” trick is the bridge between arrays and hashing.
More practice: Valid Sudoku (36) MEDIUM — canonical keys for rows, columns and boxes; Subarray Sum Equals K (560) MEDIUM — prefix sum + hash map.
★Practice problems
Start with plain array and string traversal, then switch to sets and dictionaries. For every hashing problem, also say what the brute-force version would cost. There are 48 problems, grouped by level and topic: 45 easy and 3 medium. Each link opens the problem on the platform where you can submit and test your solution. Tick a problem when you have solved it, and use “My solution” to save your code, approach, complexity and notes to revise later.
Beginner37 problems
No algorithm knowledge needed — loops, conditions and indexing.
Array Operations
Traverse, count, reverse and rotate with simple loops and index arithmetic.
String Operations
Strings as arrays of characters: scan, transform and compare.
Basic10 problems
Direct applications of this chapter’s core idea.
Arrays
In-place edits and O(1) extra space on contiguous arrays.
Hashing
Sets and dictionaries for O(1)-average membership, counting and grouping.
Intermediate1 problem
The pattern combined with one more idea, or applied to a less obvious setup.
Array/String Operations
Medium-level array and string reasoning without a named pattern.
NAdvanced concepts
N.1 Better probe sequences
Linear probing suffers from primary clustering: one collision makes nearby collisions more likely. [13] Variants change the probe step — quadratic probing, double hashing (a second hash decides the step), and CPython’s perturbed recurrence that mixes in higher hash bits. [11] Robin Hood hashing keeps linear probing but, on collision, lets the key that is farthest from its home bucket take the slot, which evens out probe lengths. [12]
N.2 Universal hashing
Instead of one fixed hash function, pick one at random from a family where any two keys collide with probability ≤ 1/m, for example hab(k) = ((ak + b) mod p) mod m. Then no input is bad for most choices, and the expected O(1) bound holds for every input. [2]
N.3 Cuckoo hashing
Each key has two possible homes, T₁[h₁(x)] and T₂[h₂(x)]. Insertion may kick an existing key to its other home (like a cuckoo chick), but lookup checks just two cells, giving worst-case constant lookup time. It was introduced by Pagh and Rodler in 2001. [14]
N.4 Bloom filters
A Bloom filter is a bit array plus k hash functions that answers “definitely not in the set” or “possibly in the set”. False positives are possible but false negatives are not, in exchange for using far less memory than storing the keys. It was conceived by Burton Howard Bloom in 1970. [15]
N.5 Consistent hashing
With hash(k) % m, changing the number of servers m moves almost every key. Consistent hashing places keys and servers on a circle so that a resize moves only about n/m keys on average; it was introduced by Karger et al. in 1997 and underpins many distributed caches and databases. [16]
N.6 Rolling hashes and hash flooding
Polynomial rolling hashes let you update a substring’s hash in O(1) as a window slides, the basis of Rabin–Karp string search; collisions occur with probability about 1/M per comparison, so careful code uses two moduli. [22] On the defensive side, hash flooding — sending many keys that collide — turns O(1) tables into O(n) ones; PEP 456 made SipHash the default string hash in Python 3.4 to make such collisions infeasible to predict. [10]
ONotebook-ready summary
First, the whole idea on one page — copy this sheet into your notebook. The detailed revision notes follow it.
A row of equal-size slots stored next to each other in memory. Any slot can be reached directly by its index.
One multiply + one add → O(1) access, no searching.
A hash function turns a key into a number; the number picks a bucket in an array.
Equal keys must give equal hashes. Keys must be hashable (immutable).
Two keys, same bucket. Two fixes:
- Chaining — each bucket holds a small list.
- Open addressing — probe the next free slot (Python’s dict).
A[3] → 1000 + 3 × 8 = 1024 → read 40
Insert at front → shift everyone right: O(n). Append at end: O(1) amortized.
Arrays find by position in O(1); hash tables find by key in O(1) on average. Spend memory, skip the search.
| A[i] | O(1) |
| append | O(1)* |
| insert / delete middle | O(n) |
| x in list | O(n) |
| dict / set get, put, in | O(1) avg |
| hash worst case | O(n) |
* amortized — doubling copies < 2n
- 👀Seen-set → duplicates
- 🎯Complement → Two Sum
- 🔢Counter → anagrams, top-k
- 🔑Canonical key → grouping
- ➕Prefix sum + map → subarrays
- 📋
listdynamic array - 📖
dictkey → value - 🧺
setmembership - 🔢
Countercounting - 🗂
defaultdict(list)grouping
x in listinside a loop = O(n²).- List keys →
TypeError; use tuples. [[0]*n]*mshares rows.- Don’t change a dict while looping it.
Detailed revision notes
1 · Definitions
- Array: contiguous, equal-size slots;
addr = base + i·size→ O(1) access. - Dynamic array (Python
list): array of references + spare capacity; doubles (grows geometrically) when full. - Hash table: buckets array + hash function;
index = hash(k) % m; α = n/m.
2 · Core ideas
- Position is computed, never searched.
- Contiguity ⇒ middle insert/delete shifts Θ(n − i) items.
- Rare Θ(n) resize, spread over many ops ⇒ amortized O(1).
- Collisions are certain (birthday effect) — resolve by chaining or probing.
3 · Picture to draw
4 · Key properties
- Equal keys ⇒ equal hashes (the one hard rule).
- Mutable objects (list, dict, set) are unhashable.
- Open addressing needs tombstones on delete; α must stay < 1.
- Python dict: open addressing, insertion-ordered (3.7+), SipHash for str (3.4+).
5 · Complexity
| Op | Array / list | Hash (dict/set) |
|---|---|---|
| Access by index | O(1) | — |
| Find by value/key | O(n) | O(1) avg, O(n) worst |
| Insert | O(1)* end, O(n) middle | O(1) avg* |
| Delete | O(1) end, O(n) middle | O(1) avg |
| Space | Θ(n) | Θ(n) (+ free slots) |
6 · Python syntax
seen = set(); if x in seen: …; seen.add(x)cnt = Counter(nums); cnt.most_common(k)groups = defaultdict(list); groups[key].append(w)d.get(k, 0) + 1·grid = [[0]*c for _ in range(r)]
7 · Load-factor maths
- Chaining: expected chain ≤ 1 + (n−1)/m = O(1 + α).
- Linear probing: hit ≈ ½(1 + 1/(1−α)), miss ≈ ½(1 + 1/(1−α)²).
- Doubling: 1 + 2 + 4 + … < 2n copies.
8 · Applications
- Python namespaces, DB hash indexes (= only), caches, de-duplication, Bloom filters, consistent hashing.
9 · Interview takeaways
- Brute force O(n²)? Ask: “can a set/dict remember what I’ve seen?”
- Say “O(1) on average” and state the O(n) extra space.
- Need order or ranges? → sort or a BST instead.
- Values in 1..n? → the array itself can be the hash table.
PKnowledge assessment
Attempt everything before opening the answer section.
Conceptual questions
- Why can an array read
A[i]in constant time, while a linked list cannot? - Explain the difference between amortized O(1) and expected O(1), using list append and dict lookup as examples.
- Why does an open-addressing table need tombstones on deletion, while a chaining table does not?
- Why are Python lists not allowed as dictionary keys? What should you use instead?
- Name two situations where a balanced BST or sorted array is a better choice than a hash table.
Dry-run exercises
- Using the toy hash (sum of char codes mod 8) and linear probing in an 8-slot table, insert
"ab","ba","c"in that order. Codes: a = 97, b = 98, c = 99. Which slot does each key end up in? - A dynamic array starts with capacity 1 and doubles when full. How many element copies happen during the first 17 appends? What is the final capacity?
- Trace the one-pass Two Sum on
nums = [4, 1, 5, 3],target = 8: showindex_ofafter each step and the returned answer.
Coding problems
- Write
first_unique_char(s)returning the index of the first non-repeating character ins, or −1. Target O(n). - Write
intersection_with_counts(a, b)returning the multiset intersection (each value appears min(count in a, count in b) times). - Write
is_isomorphic(s, t): can the characters ofsbe replaced one-to-one to gett? (e.g. “egg” → “add” is True, “foo” → “bar” is False.)
Practical engineering scenario
Your API receives about 50 000 events per second, each with an event_id string. Duplicates (retries) can arrive up to 10 minutes after the original and must be dropped. Memory per server is limited. Design the de-duplication: which structure(s), how you bound memory, what happens when a server restarts, and what the time cost per event is.
Answers
Conceptual answers
- An array’s elements are contiguous and equally sized, so the address of element i is
base + i·size— one computation. A linked list’s nodes are scattered; the only way to reach node i is to follow i “next” pointers, Θ(i). [1] - Amortized is a guarantee about the total cost of any sequence of operations: n appends always cost O(n) in total, even though one append may be O(n). Expected is an average over the randomness of the hash function: a single dict lookup is O(1) in expectation but could be O(n) if unlucky or attacked. [1][2]
- In open addressing a search stops at the first empty slot. Emptying a deleted slot could break the probe path of keys stored after it, making them unfindable; a tombstone keeps the path intact. In chaining each bucket’s list is independent, so removal just unlinks the entry. [11]
- Lists are mutable: if a key’s contents changed, its hash would change and the entry would sit in the wrong bucket forever. Use a tuple (or frozenset). [5][8]
- Any two of: you need sorted iteration; range queries (“all keys between a and b”); min/max or predecessor/successor; strict worst-case O(log n) guarantees; keys that are not hashable but are comparable.
Dry-run answers
- "ab" = 97+98 = 195, 195 mod 8 = 3 → slot 3. "ba" also = 195 → 3 is taken → slot 4. "c" = 99, 99 mod 8 = 3 → 3 taken, 4 taken → slot 5.
- Resizes happen when appending items 2, 3, 5, 9 and 17, copying 1 + 2 + 4 + 8 + 16 = 31 elements; final capacity 32. (Check: 31 < 2 × 17 = 34.)
- i=0, x=4: need 4, not in {} → store {4:0}. i=1, x=1: need 7, not found → {4:0, 1:1}. i=2, x=5: need 3, not found → {4:0, 1:1, 5:2}. i=3, x=3: need 5, found at 2 → return [2, 3]. (Note that at i=0, 4 + 4 = 8 but 4 must not pair with itself — checking before storing prevents it.)
Coding answers
from collections import Counter
def first_unique_char(s):
count = Counter(s)
for i, ch in enumerate(s):
if count[ch] == 1:
return i
return -1 # O(n) time, O(k) space
def intersection_with_counts(a, b):
common = Counter(a) & Counter(b) # min of counts
return list(common.elements()) # O(len(a) + len(b))
def is_isomorphic(s, t):
if len(s) != len(t):
return False
fwd, back = {}, {}
for x, y in zip(s, t):
if fwd.setdefault(x, y) != y or back.setdefault(y, x) != x:
return False
return True # two maps enforce one-to-one
# first_unique_char("leetcode") -> 0 ; ("aabb") -> -1
# intersection_with_counts([1, 2, 2, 1], [2, 2]) -> [2, 2]
# is_isomorphic("egg", "add") -> True ; ("foo", "bar") -> FalseEngineering scenario — a model answer
About 50 000 × 600 s = 30 million IDs live in any 10-minute window. Options:
- Exact: a hash map
event_id → timestampplus expiry. Use time buckets (e.g. one set per minute, keep the last 11) so expiry drops a whole set in O(1) per bucket instead of scanning. Cost per event: expected O(1) for the membership check and insert. Memory is proportional to 30 M IDs — tens of GB for strings in Python, so store a fixed-size 64-bit digest of the ID instead of the string, or move this state into a shared store (e.g. Redis with per-key TTL) so it also survives restarts and is shared by all servers. - Approximate: rotating Bloom filters (one per minute). Memory drops dramatically, and there are no false negatives — but a small false-positive rate means a few new events would be wrongly dropped, which is acceptable only if the business allows it. [15]
- Restarts: in-process structures are lost; either accept a brief window of duplicates, persist periodically, or use the shared store.
- Security: IDs come from clients, so use a randomised/keyed hash (Python’s default string hash already is) to avoid hash flooding. [10]
QReferences & further reading
- E. Demaine, J. Ku, J. Solomon, “Lecture 2: Data Structures,” MIT 6.006 Introduction to Algorithms, Spring 2020, MIT OpenCourseWare. Static and dynamic array sequences, Python list as a dynamic array, resizing, amortized analysis (Sections B, D, F, G, H, K).
- E. Demaine, J. Ku, J. Solomon, “Lecture 4: Hashing,” MIT 6.006, Spring 2020, MIT OpenCourseWare. Direct access, hash functions, chaining, universal hashing family, expected chain length 1 + (n−1)/m, load factor, rebuild and amortization (Sections B, C, F, G, H, N).
- R. Sedgewick, K. Wayne, “3.4 Hash Tables,” Algorithms, 4th ed., Princeton University. Hash function requirements, separate chaining, linear probing, load factor, probe-count formulas under uniform hashing (Sections B, D, F, G).
- Python Software Foundation, “How are lists implemented in CPython?”, Design and History FAQ. Lists are variable-length arrays of references; size-independent indexing; over-allocation on growth (Sections D, F, H, I).
- Python Software Foundation, “How are dictionaries implemented in CPython?”, Design and History FAQ. Dicts as resizable hash tables using hash(); why keys must be immutable (Sections B, F, I, P).
- Python Software Foundation, “Time complexity of operations on built-in types”, Python 3 documentation. Costs of list insert/pop O(n−k), append amortized O(1), x in list O(n), dict/set average O(1) and worst O(n), slicing (Sections C, D, F, H, L).
- Python Software Foundation,
object.__hash__, Python Language Reference — Data model. Equal objects must have equal hashes; overriding __eq__ without __hash__ makes a class unhashable (Sections B, F, I, L). - Python Software Foundation, “hashable,” Glossary. Definition of hashable; mutable containers are not hashable (Sections F, L, P).
- Python Software Foundation, “Mapping Types — dict,” Built-in Types. Insertion order guaranteed since 3.7; modifying during iteration may raise RuntimeError (Sections F, I, L).
- C. Heimes, “PEP 456 – Secure and interchangeable hash algorithm,” Python Enhancement Proposals, final for Python 3.4. SipHash as default str/bytes hash; motivation of hash-collision DoS (Sections F, G, I, J, N, P).
- CPython developers,
Objects/dictobject.c, CPython source code (GitHub). Open addressing, Unused/Dummy/Active slot states, probe recurrence and PERTURB_SHIFT (Sections F, I, N, P). - Wikipedia contributors, “Hash table” (secondary overview, cross-checked with [2], [3]). Luhn’s 1953 IBM memo, load factor definition, resizing by doubling, Robin Hood hashing (Sections B, F, N).
- Wikipedia contributors, “Linear probing” (secondary; cross-checked with [3]). Knuth’s 1963 analysis; primary clustering (Sections B, D, N).
- Wikipedia contributors, “Cuckoo hashing” (secondary). Pagh & Rodler 2001; two-location lookup with worst-case O(1) (Sections B, N).
- Wikipedia contributors, “Bloom filter” (secondary). Bloom 1970; false positives possible, no false negatives (Sections B, J, N, P).
- Wikipedia contributors, “Consistent hashing” (secondary). Karger et al. 1997; only about n/m keys remapped on resize (Sections B, J, N).
- PostgreSQL Global Development Group, “Hash Indexes,” PostgreSQL documentation. Hash indexes support only the = operator (Section J).
- Python Software Foundation, “Python Scopes and Namespaces,” The Python Tutorial §9.2. Most namespaces are implemented as dictionaries (Sections B, J).
- Python Software Foundation,
collections.Counter, Python 3 documentation. dict subclass for counting hashable objects; most_common (Sections I, M). - Python Software Foundation, “How do I create a multidimensional list?”, Programming FAQ. [[x]*n]*m creates references to the same row (Section L).
- Python Software Foundation, “Common Sequence Operations,” Built-in Types, note 2. s * n references items rather than copying them (Sections I, L).
- CP-Algorithms, “String Hashing”. Polynomial rolling hash; collision probability and double hashing (Sections F, N).
Practice problem sources
LeetCode problems 1, 36, 41, 49, 128, 217, 238, 242, 347 and 560 are linked at their point of use in Section M. Problem statements are owned by their respective sites.