Hash maps and sets: group, count, look up
- Say what a lookup, an insert and a delete cost in a dict or a set, on average and in the worst case, and compare that with a list scan
- Pick a key that works, a tuple or a frozenset when it has parts, and spot a key that breaks because equal things hash differently or it changes after it goes in
- Solve the three patterns behind most hash map questions (remember what you've seen, group by a computed key, count) with set, dict, defaultdict and Counter
- Normalize strings before they become keys, and say what building a key costs
- Find duplicate files by size first and then by a SHA-256 digest fed in chunks, reading as little as possible
- Explain how a Python dict works when an interviewer asks, down to buckets, probing, resizing and the worst case
Find the duplicate files
Anthropic candidates report a file deduplication question in phone screens (2 reports) and in onsite coding rounds (2 reports). One of them found the base problem easy and stumbled on the follow-ups (1 report). Level 1 reads like this:
Each string in
listingsdescribes one directory: its path, then onename:contententry for each file in it, all separated by single spaces. Writeduplicates_from_listings(listings): the groups of two or more paths whose files have exactly the same content. Sort the paths inside each group, then sort the groups.For example,
listingsholds these three strings:
"docs notes.txt:milk todo.txt:call-home""docs/old notes.txt:milk draft.txt:hello""tmp scratch.txt:call-home"A file's path is its directory, a slash and its name. So the answer is
[["docs/notes.txt", "docs/old/notes.txt"], ["docs/todo.txt", "tmp/scratch.txt"]]. Contents compare exactly:Milkandmilkare different files. A content can hold colons, likestandup.txt:09:30, and it can be empty, likea.log:.
Level 2 takes the content off the disk. Each file has a size that costs nothing and a read() that costs a full pass, and the tests count the passes and the memory. Level 3 makes the files too big to read at once, so the content comes in pieces. Then come the follow-ups: is the job waiting on the disk or busy on the CPU, what changes for a hundred million files, and does a matching digest prove two files are equal?
You don't write it yet. Every level comes down to one question, asked fast: have I seen this before? So the lesson starts with sets and dicts, and builds up to keys for whole files. At the end you solve the whole problem, level by level, in an interview simulation with a 40-minute timer.
Hash maps come first because almost every lesson after this one uses them. The sliding window keeps its counts in a dict, the grid search keeps the cells it has seen in a set, and the database in the coding builds, where small systems grow in levels, is a dict of dicts.
A set finds a value without a scan
Many coding questions get easy once you can answer one question fast: have I seen this before? A list answers it slowly. A set or a dict answers it in about the same time, whether it holds ten items or ten million.
A list checks every item, and a set looks in one place
ids = list(range(n))
id_set = set(ids)
# compares -1 with all n elements
-1 in ids
# hashes -1, then looks in one place
-1 in id_set
Each row below looks for -1, which isn't there, so the list has to check everything.
-1 in a list of 1,000 took 3.7 µs. About how long in a list of 1,000,000?
The hash picks a bucket, so a lookup is O(1) on average
How can a set skip the scan? Before it stores a key, it turns the key into a number, and the number says where the key goes.
keys = [12, 33, 7, 42]
print([hash(k) for k in keys])
print([hash(k) % 8 for k in keys])
For a small int, hash(k) is k. A table of 8 buckets files a key under hash(k) % 8. Which bucket does 42 go in?
To check whether 33 is in the table, how many of the other keys does the lookup compare it with?
Collisions stay rare because the table is never more than two thirds full
Now add 26 to the table of 8 buckets. 26 % 8 is 2, and 42 is already in bucket 2. Two keys that want the same bucket are a collision. The table has to put 26 in another bucket, by a fixed rule, and find it there later.
What matters for now is how often it happens. CPython keeps at most two thirds of the buckets full, and grows the table when it gets there. So most lookups land on the right key on the first try.
That gives two numbers for every operation:
- The average case is the cost when the hash spreads the keys evenly over the buckets, which ordinary keys do. A lookup, an insert and a delete each cost O(1).
- The worst case is when the keys pile into the same buckets. The Python docs say that when every key hashes to the same value, each of those O(1) operations takes O(n) time instead. A class whose
__hash__returns the same number for every object does exactly that.
The free buckets cost memory. A set's own table for a million integers is about 4 times a list's:
The dict is about 5 times. That's before the integers themselves, which all three share.
Building costs time too. set(ids) took 11.8 ms for a million integers, about three full list scans.
So a set pays off when you look up many times. If you check one value once, scan the list.
Each bucket has to be its own list. [[] for _ in range(n)] makes n separate empty lists: it's a list comprehension, an expression followed by a for that says how many times to build it. [[]] * n looks the same but repeats one list n times, so appending to any bucket appends to all of them.
In the editor, write bucket_table(keys, n): n empty buckets, with every key appended to bucket hash(key) % n. Then write collisions(table): how many keys landed in a bucket that already held a key.
Remember what you've seen
The first pattern is the one you'll use most, and part 1 of the blank-editor lesson ended on it. Walk the input once, and keep a seen-set: a set of everything you've passed.
One pass with a seen-set replaces comparing every pair
Is there a duplicate in this list?
# compare every pair
def has_duplicate_pairs(items):
for i in range(len(items)):
for j in range(i):
if items[i] == items[j]:
return True
return False
The faster way walks the list once and keeps a set of what it has passed. For each item, ask whether it's already in the set: if it is, that's a duplicate, and if not, add it. Here it is on a short input, one step per item:
Item of ["b", "a", "c", "a"] | seen, before the check | In seen? |
|---|---|---|
| "b" | { } | no: add "b" |
| "a" | {"b"} | no: add "a" |
| "c" | {"b", "a"} | no: add "c" |
| "a" | {"b", "a", "c"} | yes: return True |
The every-pair version compares each item with every item before it. With no duplicate, that's pairs, n times n minus 1, halved: 499,500 for a thousand items.
The seen-set version hashes each item once.
Keep the loop, but make seen a list. What does each item in seen cost now?
A list as the seen-set is still O(n²)
There's a third version that trips people up. It's the same loop with seen = [] and seen.append(item). It reads like the seen-set version, but item in seen on a list is a scan. So it's every-pair in disguise.
On lists of distinct strings, no duplicate, best of several runs:
| n | Pairs compared | Every pair | List as seen | Seen-set |
|---|---|---|---|---|
| 1,000 | 499,500 | 10.1 ms | 2.8 ms | 0.029 ms |
| 2,000 | 1,999,000 | 41.7 ms | 9.8 ms | 0.071 ms |
| 4,000 | 7,998,000 | 178.2 ms | 42.1 ms | 0.136 ms |
| 8,000 | 31,996,000 | 753.5 ms | 178.4 ms | 0.305 ms |
Double n, and the every-pair and list times grow about four times. That's O(n²).
The seen-set grows about two times. That's O(n). At 8,000 items the seen-set is about 2,500 times faster than comparing every pair, and the gap keeps widening.
You can see why by counting what each version asks of the items. Give 2,000 distinct objects an __eq__ that counts its calls. The list as seen called it 1,999,000 times. The seen-set called it 0 times.
A set compares two keys with == only when their hashes match. These objects hash distinct integers, so no two hashes ever matched.
In the editor, finish unique_in_order(items): each item's first occurrence, in the order they first appear, so [3, 1, 3, 2, 1] gives [3, 1, 2]. Check each item against seen, not against out.
Finish unique_in_order(items): return the first occurrence of each item, in the order they first appear. [3, 1, 3, 2, 1] gives [3, 1, 2]. Check against a seen-set, not the output list.
dict.fromkeys drops repeats and keeps first-seen order
You just wrote the dedup loop by hand. Python has a one-line version that keeps the same order.
items = [3, 1, 3, 2, 1]
print(list(dict.fromkeys(items)))
print(list(set(items)))
What does list(dict.fromkeys([3, 1, 3, 2, 1])) give?
What can be a key
Strings and numbers work as keys. Not every value does, and the reason is the hash.
A key must keep its hash, and equal keys must hash equal
{[1, 2]: "x"}
TypeError: unhashable type: 'list'
A list can't be a key. A tuple with the same items can:
print({(1, 2): "x"})
{(1, 2): 'x'}
A hash table finds a key in three steps. Each step leans on a promise:
Python's glossary states both promises. A key's hash never changes during its lifetime. And keys that compare equal have the same hash.
Python's immutable built-ins keep both. So ints, floats, strings, bytes, frozensets, and tuples of hashable things can all be keys. Mutable containers, like lists, sets and dicts, can't.
Equal keys are one key, even across types:
print({1: "int", 1.0: "float", True: "bool"})
{1: 'bool'}
1, 1.0 and True compare equal, so Python promises they hash equal. The dict treats them as one key:
| Write | The dict after it |
|---|---|
1: "int" | {1: 'int'} |
1.0: "float" | {1: 'float'}: 1.0 == 1, the same key, a new value |
True: "bool" | {1: 'bool'}: True == 1, the same key, a new value |
The first spelling of the key stays, and the last value wins.
To catch an error instead of stopping, put the call in a try block and name the error in except:
try:
hash([1, 2])
print("hashable")
except TypeError:
print("not hashable")
not hashable
The try block runs until a line raises. If the error is the one the except line names, Python runs that block and carries on.
In the editor, write can_be_key(value): True when hash(value) works, and False when it raises TypeError. Then write distinct_keys(values): how many keys a dict holds once each value goes in as a key, where equal values like 1 and 1.0 share one key.
A tuple holds a key with parts, and a frozenset one with no order
Many keys have more than one part: a grid cell has a row and a column, and a file has a size and a digest. Two hashable containers hold such keys, and they differ on one thing, order.
print(("ann", "bo") == ("bo", "ann"))
print(frozenset({"ann", "bo"}) == frozenset({"bo", "ann"}))
False
True
When a key has parts, like a grid cell's row and column or a file's size and digest, put them in a tuple: (row, col), (size, digest).
A tuple keeps its order, so ("ann", "bo") and ("bo", "ann") are different keys. When order shouldn't matter, as with a friendship or an undirected edge, use a frozenset, the immutable set. The two frozensets above are equal, and they hash the same.
A frozenset keeps each name once: frozenset(("ann", "ann")) holds one name. When repeats matter, use a sorted tuple, tuple(sorted(pair)), instead.
In the editor, write distinct_friendships(pairs): how many different friendships a log of name pairs holds. ("ann", "bo") and ("bo", "ann") are the same friendship, so the key must ignore order.
A friendship log lists each friendship as a pair of names, from either side and sometimes from both: ("ann", "bo") and ("bo", "ann") are one friendship. Write distinct_friendships(pairs) to return how many different friendships the log holds.
Your own class must hash what it compares
Define __eq__ without __hash__, and Python makes your objects unhashable:
class OnlyEq:
def __init__(self, name):
self.name = name
def __eq__(self, other):
return self.name == other.name
{OnlyEq("milk")}
TypeError: unhashable type: 'OnlyEq'
That's the safe outcome. The dangerous one is a __hash__ that disagrees with __eq__:
class Tag:
def __init__(self, name):
self.name = name
def __eq__(self, other):
return self.name.casefold() == other.name.casefold()
def __hash__(self):
# bug: hashes the raw name
return hash(self.name)
print(Tag("Milk") == Tag("milk"))
print(len({Tag("Milk"), Tag("milk")}))
Tag compares names with casefold but hashes the raw name. How many items does {Tag("Milk"), Tag("milk")} hold?
A key that changes after it goes in can't be found
A key's hash has to stay the same for as long as the key sits in the table. Here is what happens when it doesn't.
class Box:
def __init__(self, label):
self.label = label
def __eq__(self, other):
return self.label == other.label
def __hash__(self):
return hash(self.label)
box = Box("a")
boxes = {box}
box.label = "z"
print(box in boxes, Box("a") in boxes, Box("z") in boxes, len(boxes))
A Box with label "a" goes in a set, and then its label changes to "z". Is Box("z") in the set?
Group by a computed key
The second pattern puts things that have something in common into one list each. The something is a key you compute from each item. The dict maps each key to its list.
A grouping dict maps each computed key to a list
Here's a log grouped by host:
events = ["web-1:timeout", "db-1:restart", "web-1:restart", "cache-1:timeout", "db-1:disk:full"]
by_host = {}
for line in events:
host, _, event = line.partition(":")
if host not in by_host:
by_host[host] = []
by_host[host].append(event)
for host, got in by_host.items():
print(host, got)
web-1 ['timeout', 'restart']
db-1 ['restart', 'disk:full']
cache-1 ['timeout']
The dict fills in one line at a time:
| Line | Key | What happens | The key's list |
|---|---|---|---|
| web-1:timeout | web-1 | a new key, a new list | [timeout] |
| db-1:restart | db-1 | a new key, a new list | [restart] |
| web-1:restart | web-1 | append | [timeout, restart] |
| cache-1:timeout | cache-1 | a new key, a new list | [timeout] |
| db-1:disk:full | db-1 | append | [restart, disk:full] |
Two details in that loop get people. The first is the split:
print("db-1:disk:full".split(":"))
print("db-1:disk:full".partition(":"))
['db-1', 'disk', 'full']
('db-1', ':', 'disk:full')
split(":") cuts at every colon. Unpack its three parts into two names, host, event = ..., and you get ValueError: too many values to unpack (expected 2). partition(":") cuts at the first colon only, and always returns three parts.
The second detail is the empty list for a new key.
Write by_host[host] = [event] on every line, in place of the append. How many of the 5 events are left at the end?
setdefault and defaultdict make the empty list for you
The if-not-in step takes three lines. Python has two shorter ways:
# one dict method
by_host.setdefault(host, []).append(event)
from collections import defaultdict
# a dict that makes missing values
by_host = defaultdict(list)
by_host[host].append(event)
All three build the same dict. defaultdict(list) reads best when the whole job is grouping. It calls list() to make a value whenever you read a key that isn't there, and keeps it.
That's handy while grouping, and a trap afterwards. Just looking up a key adds it:
from collections import defaultdict
by_host = defaultdict(list)
print(by_host["no-such-host"])
print(dict(by_host))
[]
{'no-such-host': []}
When you only want to check, ask "other" in by_host or by_host.get("other").
In the editor, by_host is a defaultdict(list) with one event for web-1. Write quiet_hosts(by_host, hosts): the hosts, in the order given, that have no events. Check with in or get, so that by_host gains no keys.
Sorted letters give every anagram the same key
Anagrams use the same letters: listen, silent, enlist, inlets. Comparing every pair of words costs O(n²) comparisons. Grouping needs one key per word, equal exactly when two words are anagrams. The sorted letters are such a key:
words = ["listen", "silent", "enlist", "google", "inlets", "banana"]
groups = defaultdict(list)
for word in words:
groups["".join(sorted(word))].append(word)
for key, group in groups.items():
print(key, group)
The key is "".join(sorted(word)). What key does "listen" get?
Normalize a string key, but only what the problem calls the same
The anagram key compares letters exactly, so capital letters and special characters change it.
print("".join(sorted("Listen")), "".join(sorted("silent")))
print("Straße".lower(), "Straße".casefold())
Do "Listen" and "silent" get the same sorted-letters key?
Sorting builds the fastest key for words, counting for long strings
Building a key costs time. Here are two keys that are equal exactly for anagrams of lowercase words. A third, count_key, counts how many a's, b's and so on up to z's a word has, and you'll write it below:
from collections import Counter
def sorted_key(word):
return "".join(sorted(word))
def counter_key(word):
return tuple(sorted(Counter(word).items()))
Timed on a random lowercase string of length k:
| k | sorted_key | count_key | counter_key |
|---|---|---|---|
| 8 | 0.29 µs | 0.47 µs | 1.03 µs |
| 1,000,000 | 91.4 ms | 46.9 ms | 23.6 ms |
Sorting is O(k log k), and the counting keys are O(k). Yet at word length, sorting is fastest. It runs in C, while count_key loops in Python and Counter has more setup.
On a million characters the counting keys win. Counter, which counts in C, is nearly four times faster than sorting.
So for n words of length k, grouping by sorted letters costs O(n k log k). Sorting and comparing every pair costs O(n² k log k).
Hashing a string is O(k) too, but Python caches a string's hash. The first hash() of a 100,000,000-character string took 35.0 ms, and the second 0.54 µs.
In the editor, finish count_key(word), the counting key from the timings. Add 1 to counts[ord(ch) - ord('a')] for each letter, and return the counts as a tuple, so that the key is hashable.
Group anagrams with a key built from letter counts instead of sorted letters. The idea is drawn out first, and the code starts at 4:35.
Count first, then decide
The third pattern counts how often each key appears. Some questions need those counts for the whole input before they can decide about any one item.
A count is a dict from each key to a number
words = "the cat and the hat and the bat".split()
counts = {}
for word in words:
counts[word] = counts.get(word, 0) + 1
print(counts)
{'the': 3, 'cat': 1, 'and': 2, 'hat': 1, 'bat': 1}
counts.get(word, 0) gives 0 for a word you haven't seen yet.
Counter counts in one call, and a missing count is 0
collections.Counter does the same loop in one call, and adds what you usually want next:
from collections import Counter
counts = Counter(words)
print(counts.most_common(2))
print(counts["dog"], "dog" in counts)
print(Counter("listen") == Counter("silent"), Counter("aab") == Counter("abb"))
[('the', 3), ('and', 2)]
0 False
True False
most_common(2)gives the two biggest counts.- A missing key reads as 0, not a
KeyError. Unlikedefaultdict, reading it doesn't add it. - Two Counters are equal when every count matches. That's an anagram test in one line.
Pick the container by what each key holds
| Each key holds | Container | In this lesson |
|---|---|---|
| nothing: seen or not | set | the seen-set |
| one value | dict | size → position |
| a group of items | defaultdict(list) | host → its events |
| a count | Counter | word → how often |
Any of them works anywhere. The right one deletes lines and says what you mean.
In the editor, finish count_words(words) with counts.get(word, 0) + 1. Then write same_letters(a, b): True when the two strings are anagrams, by comparing two Counters.
A seen-set can't answer what needs the whole input
A seen-set answers questions about what came before. Some questions need the whole input first.
word = "swiss"
counts = Counter(word)
print(next(ch for ch in word if counts[ch] == 1))
w
The first character that appears exactly once in "swiss" is w. You can't know that at the first s, because the second s hasn't come yet. So count everything in one pass, then decide in a second. A seen-set can't do this: at any moment it only knows the past.
The practice problem hits exactly this. Two files can be duplicates only if they have the same size. A size is free to read, and the content is not. So you want to open only the files whose size another file shares.
Try it with a seen-set on five files and their sizes:
files = [("a.jpg", 17), ("b.jpg", 17), ("c.txt", 10), ("d.mov", 9000), ("e.txt", 10)]
seen, flagged = set(), []
for path, size in files:
if size in seen:
flagged.append(path)
seen.add(size)
print(flagged)
['b.jpg', 'e.txt']
It misses a.jpg and c.txt, the first file of each size. When you meet them, their twin hasn't come along yet. Counting the sizes first gets all four:
| File | Size | Seen-set before | Seen-set says | Size count |
|---|---|---|---|---|
| a.jpg | 17 | { } | no: missed | 2: read |
| b.jpg | 17 | {17} | yes | 2: read |
| c.txt | 10 | {17} | no: missed | 2: read |
| d.mov | 9000 | {17, 10} | no | 1: skip |
| e.txt | 10 | {17, 10, 9000} | yes | 2: read |
A generator hands out its values one at a time, and only once:
g = (n for n in [1, 2])
print(list(g), list(g))
[1, 2] []
The first list(g) used the values up, so the second gets nothing. A function that walks a generator twice sees an empty second pass.
In the editor, write worth_reading(files). files holds (path, size) pairs, and it may be a generator that you can walk only once. Return the paths whose size at least one other file shares, in the order they came.
Write worth_reading(files). files is an iterable of (path, size) pairs. Return the paths whose size at least one other file shares, in the order they came. files may be a generator, which you can only walk once.
A digest is a key for a whole file
Two files of the same size can still differ, so the content has to decide. But the content can't be the key. A 2 GiB file as a dict key is 2 GiB held in memory, and comparing two such keys reads both.
SHA-256 gives 32 bytes for any input, and the same bytes on every run
import hashlib
print(hashlib.sha256(b"milk").hexdigest())
print(hashlib.sha256(b"Milk").hexdigest())
8825e76530f87ff5c737b3254c6936bc0a90bba3a10a91bbba739268208d378a
8189b8409b18b1ef215ec2f2d8da515cdc7cc21a4b7cd35482b66bede2275d02
A digest is a short value that stands for the content. It comes from a cryptographic hash function, like SHA-256 in hashlib. Any number of bytes go in, and 32 come out. Change a single byte, and you get a completely different digest.
.digest() gives the 32 raw bytes. .hexdigest() gives the same as 64 hex characters. Either one is a fine key.
Why not Python's own hash()? It isn't built for this, for two reasons.
First, it's 64 bits. Among a billion files, the chance that two share a value is about 3 in 100, as the follow-ups work out.
You print hash("milk") in two fresh Python processes. Do you get the same number?
Count the sizes, then key the rest by size and digest
Put the size and the digest together. Here are eight small files, with the content shown so you can check the answer:
FILES = {
"photos/beach.jpg": b"sunset over water",
"photos/beach-copy.jpg": b"sunset over water",
"backup/beach.jpg": b"sunset over water",
"docs/notes.txt": b"milk, eggs",
"docs/todo.txt": b"call home!",
"backup/notes.txt": b"milk, eggs",
"video/trip.mov": b"v" * 9000,
"tmp/empty.log": b"",
}
The size counts are {17: 3, 10: 3, 9000: 1, 0: 1}. So the movie and the empty log are never opened. The six others get a key of (size, digest):
docs/notes.txt and docs/todo.txt are both 10 bytes. Are they duplicates?
Feed a file in pieces, and the digest doesn't change
Level 3 makes the files too big to read at once. A digest doesn't need the whole file in memory, because it can take the bytes a piece at a time.
sha = hashlib.sha256()
sha.update(b"mi")
sha.update(b"lk")
print(sha.digest() == hashlib.sha256(b"milk").digest())
True
A hash object takes the bytes in pieces. The hashlib docs promise that many update calls equal one call with all the pieces joined. So where you cut doesn't matter:
Cut of b"milk" | Calls | Digest |
|---|---|---|
| [mi][lk] | update(b"mi"), update(b"lk") | the same |
| [m][ilk] | update(b"m"), update(b"ilk") | the same |
| no cut | update(b"milk") | the same |
A file may be too big to read at once, and you never need to. Three ways to hash a file, timed on a 256 MiB file of random bytes that the operating system already had cached, with peak memory from tracemalloc:
def digest_whole(path):
with open(path, "rb") as f:
return hashlib.sha256(f.read()).digest()
def digest_of(path, piece=1 << 20):
sha = hashlib.sha256()
with open(path, "rb") as f:
while chunk := f.read(piece):
sha.update(chunk)
return sha.digest()
def digest_by_library(path):
with open(path, "rb") as f:
return hashlib.file_digest(f, "sha256").digest()
| Time | Peak memory | |
|---|---|---|
digest_whole | 0.159 s | 256.00 MiB |
digest_of, 1 MiB pieces | 0.128 s | 2.00 MiB |
hashlib.file_digest | 0.130 s | 0.26 MiB |
All three give the same digest. Reading in pieces is no slower, and holds 2 MiB instead of 256. hashlib.file_digest, new in Python 3.11, does the same loop for you on a real file.
In the editor, write fingerprint(chunks): one SHA-256 digest, as the 32 raw bytes, of all the bytes pieces in chunks, in order. Feed every piece to one hash object, and never join them.
Write fingerprint(chunks): the SHA-256 digest, as the 32 raw bytes, of all the bytes pieces in chunks joined in order. The pieces can be cut anywhere, and together they can be bigger than you want to hold, so never join them.
How a dictionary works, and when it's slow
The Python FAQ sums it up: CPython's dictionaries are hash tables that resize. Here is what happens inside one, in CPython 3.12.
A dict keeps its entries in order, and their positions in a table
A dict gets the keys 12, 33, 7 and 42, in that order. In what order does list(d) give them back?
A collision probes other slots by a fixed rule
When the slot holds a different key, CPython probes another slot. The next slot comes from the slot it just tried and from the hash's higher bits, which it feeds in a few at a time. Here's a model of that rule, small enough to run by hand on the integer keys from the start of the lesson:
# 8 slots
def slot_for(key, table, mask=7):
h = hash(key)
i, perturb = h & mask, h
while table[i] is not None:
perturb >>= 5
i = (i * 5 + perturb + 1) & mask
return i
table = [None] * 8
for key in (12, 33, 7, 42, 26):
table[slot_for(key, table)] = key
print(table)
[None, 33, 42, 26, 12, None, None, 7]
With 8 slots, a key starts at slot hash & 7. Which slot does 26 want first?
The table grows at two thirds full, so an insert is amortized O(1)
The table keeps at least a third of its buckets empty, so it has to grow as keys go in. Predict when this dict grows, then check.
A dict's table grows when it passes two thirds full. With 8 slots, which key makes it grow?
When every key has the same hash, each operation is O(n)
Now the worst case, on purpose. Give a class a hash that's always 1:
class Good:
def __init__(self, n):
self.n = n
def __eq__(self, other):
return self.n == other.n
def __hash__(self):
return hash(self.n)
class Bad(Good):
def __hash__(self):
return 1
Every Bad key wants the same slot, so each insert probes past all the keys before it.
Every key in bads hashes to the same value. Double the keys: how much longer does set(bads) take to build?
A worked example: two files that fill a disk exactly
The prompt: you have a list of file sizes, and a disk with exactly capacity free. Find two different files whose sizes add up to exactly capacity. Return their positions in the list, or None if no pair does. Here, sizes = [700, 250, 1200, 300, 450, 800] and capacity = 1500.
Clarify first. Say it out loud. Two different files, but they may have the same size. If several pairs work, any one will do, and here we return the first pair to complete as we read left to right. A single file of exactly 1500 isn't a pair.
The obvious answer. Try every pair: two nested loops, O(n²) time, O(1) extra memory. Say it, give its cost, and move on. It's the baseline the interviewer wants you to beat.
Each file's partner has a fixed size, so one pass with a dict finds it
For each file, its partner's size is fixed: need = capacity - size. So the question for each file is whether you've already seen a file of size need. That's a seen-lookup, with one twist: you need the partner's position, not just whether it exists. So it's a dict from size to position, not a set.
def fill_exactly(sizes, capacity):
# size -> position of a file that size
seen = {}
for j, size in enumerate(sizes):
need = capacity - size
if need in seen:
return seen[need], j
seen[size] = j
return None
print(fill_exactly([700, 250, 1200, 300, 450, 800], 1500))
Capacity 1500, and the sizes are 700, 250, 1200, 300, 450, 800. Which pair of positions fills it exactly first?
Two one-line bugs: inserting first, and testing with get
The order of the two lines in the loop matters. Check before you insert. Insert first, and a file can pair with itself. With [750, 100]:
| Step | Insert, then check | Check, then insert |
|---|---|---|
| j = 0 | seen: 750 → 0. Need 750: in seen, at 0 | need 750: not in seen. seen: 750 → 0 |
| j = 1 | already returned (0, 0), wrong | need 1400: not in seen. seen: 750 → 0, 100 → 1 |
| end | return None |
Checking first returns None there. It returns (0, 2) for [750, 100, 750]: two different files of the same size.
Test membership with in. if seen.get(need): reads the stored position as true or false, and position 0 is false. On [700, 250, 800] that version returns None instead of (0, 2).
Test the edges you named too: [] and [1500] both return None.
In the editor, fill_exactly has both bugs. Run it: [700, 250, 800] should give (0, 2). Fix the loop so that it checks before it inserts, and tests with in.
What interviewers ask next
These are the follow-ups the practice problem's README lists, plus two general ones.
Is it waiting on the disk or busy on the CPU?
Measure both clocks: time.perf_counter() for wall time, and time.process_time() for CPU time. Then compare them:
| Clocks | It's | So |
|---|---|---|
| wall ≈ CPU | busy on the CPU | threads: hashlib frees the GIL |
| wall ≫ CPU | waiting on the disk | read less |
Hashing the cached 256 MiB file took 0.133 s of wall time and 0.133 s of CPU. That's all CPU: SHA-256 at about 2 GB a second.
When it's busy on the CPU, threads help. The GIL is the lock that lets only one thread run Python at a time. hashlib releases it while it hashes more than 2047 bytes given in one call.
Hashing eight cached 64 MiB files on one thread took 0.268 s. About how long on 4 threads?
What about very large files?
Never read one whole. Stream it in chunks: 2 MiB of memory instead of 256, as measured above.
And add a cheap stage between the size and the full hash:
Any two files that differ in that first block are ruled out after a few KiB, instead of the whole file.
In the editor, FILES maps each path to its bytes. Write still_candidates(files, block): group the paths by their size and their first block bytes, and return the groups of two or more, sorted inside and sorted.
What about a hundred million files?
The paths fill the memory. If a path averages 100 bytes, a hundred million of them is 10 GB, before Python's overhead per string.
So keep them on disk. Write (size, path) records to a file and sort them by size with an external sort, a sort that works through the disk when the data doesn't fit in memory. Then stream through one size at a time:
Or split the work across machines by size. Each machine owns every file of the sizes given to it, so no group spans two machines.
Watch for hard links too. Two paths with the same st_dev and st_ino from os.stat are one file, not two copies.
groupby from itertools hands you each run of neighbors that share a key, one run at a time. Each run holds the whole records:
from itertools import groupby
records = [(10, "a"), (10, "b"), (17, "c")]
for size, run in groupby(records, key=lambda r: r[0]):
print(size, list(run))
10 [(10, 'a'), (10, 'b')]
17 [(17, 'c')]
A function with yield in it is a generator: each yield hands one value to the caller's loop and pauses until the loop asks for the next. In the editor, RECORDS are (size, path) pairs, already sorted by size. Finish size_runs(records): collect each run's paths in a list, and yield the list only when it holds two or more.
How would you catch a duplicate as it's written?
Keep the index, digest to path, in a store that lasts, instead of rebuilding it each night. Hash each file once it's fully written, and look the digest up. A digest already in the index is a copy of the stored path. A new one goes in.
Linux tells you when a file open for writing is closed (inotify's IN_CLOSE_WRITE). On macOS, FSEvents only says that a file changed, so hash it once it stops changing.
Content-addressed storage goes all the way: it stores each piece of content once, under its digest.
In the editor, DupIndex is that index: by_digest maps each digest to the first path stored with it. Finish on_close(path, data), which runs when a file is closed after a write. Return the stored path when the data's SHA-256 digest is already there, and otherwise store the path and return None.
Does an equal digest prove the files are equal?
Level 2 treats two files with the same size and digest as the same file. An interviewer will ask whether that's safe.
A billion files, keyed by Python's 64-bit hash(). About what chance do two of them share a key by accident?
How would you test it on real files?
Build a tree in tempfile.TemporaryDirectory(), walk it with os.walk, size files with os.path.getsize, and open them in binary mode. This version ran and passed:
import hashlib
import os
import tempfile
from collections import defaultdict
from pathlib import Path
def duplicates_under(root):
by_size = defaultdict(list)
for folder, _, names in os.walk(root):
for name in names:
path = os.path.join(folder, name)
by_size[os.path.getsize(path)].append(path)
groups = defaultdict(list)
for size, paths in by_size.items():
if len(paths) > 1:
for path in paths:
with open(path, "rb") as f:
groups[size, hashlib.file_digest(f, "sha256").digest()].append(path)
return sorted(sorted(paths) for paths in groups.values() if len(paths) > 1)
def test_duplicates_under():
files = {
"a/report.txt": b"q3 numbers",
# same bytes, another folder and name
"b/copy.txt": b"q3 numbers",
# same size, other bytes
"b/draft.txt": b"q3 guesses",
"c/empty1.log": b"",
"c/empty2.log": b"",
# a size of its own
"c/big.bin": b"x" * 5000,
}
with tempfile.TemporaryDirectory() as root:
for name, data in files.items():
path = Path(root, name)
path.parent.mkdir(parents=True, exist_ok=True)
path.write_bytes(data)
found = [[os.path.relpath(p, root) for p in group] for group in duplicates_under(root)]
assert found == [["a/report.txt", "b/copy.txt"], ["c/empty1.log", "c/empty2.log"]]
In the editor, write make_tree(root, files): each file's bytes written under root, with its folders made first. Then write walk_sizes(root): walk root with os.walk, and map each file's path, relative to root, to its size from os.path.getsize.
What's the complexity?
Say both cases. With ordinary keys, n lookups cost O(n) on average. If someone else can choose the keys, or a custom __hash__ is poor, the worst case is O(n) per lookup.
Then add the key's own cost, which people forget. Hashing a string or a file is O(length).
The duplicate finder costs O(n) to count n sizes, plus O(S) to hash the S bytes in files whose size is shared.
In the editor, write bytes_hashed(sizes): S, the total bytes of every file whose size at least one other file shares. For sizes 17, 17, 17, 10, 10, 10, 9000 and 0 that's 3 × 17 + 3 × 10 = 81. Count the sizes first.
The practice problem, start to finish
That's every piece the practice problem needs. It asks for every level from the start of the lesson, from a blank file, and the interviewer follows up after each one.
1.You check whether a value is in a collection of n items. What does each lookup cost on average with a list and with a set?
2.Which of these can be a key in a Python dict?
3.What does
{1: "int", 1.0: "float", True: "bool"}evaluate to?4.You want to open only the files whose size another file shares, so you loop once and flag a file when its size is already in a seen-set. What goes wrong on sizes 17, 17, 10, 9000, 10?
5.Two copies of the same 1 GiB file are read in chunks of different sizes. You can't hold a whole file in memory, and the keys are saved to compare with next week's scan. Which way of hashing gives both copies the same key?
6.In the two-sum loop, you write
seen[size] = jbefore checkingneed in seen. What happens with sizes[750, 100]and capacity 1500?
Where this shows up
The reports behind this lesson, each with its source.
L5 MLE candidate (dated 2024-07-03): asked how Python dictionaries work.
Practice
Sources (12)
- Glossary: hashable · Python 3.12 documentation · Oct 26, 2026
“Hashable objects which compare equal must have the same hash value.”
- Data model: object.__hash__ · Python 3.12 documentation · Oct 26, 2026
“if it defines __eq__() but not __hash__(), its instances will not be usable as items in hashable collections”
- Built-in Functions: hash · Python 3.12 documentation · Oct 26, 2026
“Numeric values that compare equal have the same hash value (even if they are of different types, as is the case for 1 and 1.0).”
- Design and History FAQ: Why must dictionary keys be immutable? · Python 3.12 documentation · Oct 26, 2026
“If the key were a mutable object, its value could change, and thus its hash could also change.”
- Design and History FAQ: How are dictionaries implemented in CPython? · Python 3.12 documentation · Oct 26, 2026
“CPython's dictionaries are implemented as resizable hash tables.”
- collections: Counter objects · Python 3.12 documentation · Oct 26, 2026
“Counter objects have a dictionary interface except that they return a zero count for missing items instead of raising a KeyError”
- Built-in Types: str.casefold · Python 3.12 documentation · Oct 26, 2026
“Casefolding is similar to lowercasing but more aggressive because it is intended to remove all case distinctions in a string.”
- hashlib: hash.update · Python 3.12 documentation · Oct 26, 2026
“Repeated calls are equivalent to a single call with the concatenation of all the arguments”
- hashlib: Hash algorithms · Python 3.12 documentation · Oct 26, 2026
“the Python GIL is released while computing a hash supplied more than 2047 bytes of data at once in its constructor or .update method”
- Command line and environment: -R · Python 3.12 documentation · Oct 26, 2026
“Hash randomization is intended to provide protection against a denial-of-service caused by carefully chosen inputs that exploit the worst case performance of a dict construction”
- Time complexity of operations on built-in types · Python 3.15 documentation · Nov 10, 2026
“In the worst case, when every key hashes to the same value, each of the O(1) operations below instead takes O(n) time.”
- Objects/dictobject.c at v3.12.16 · CPython source code · Oct 25, 2026
“To avoid slowing down lookups on a near-full table, we resize the table when it's USABLE_FRACTION (currently two-thirds) full.”