Hash Maps & Sets: Practice Questions
100 questions. Try each one yourself before checking the answer.
Short on time? Filter by Must Do for the 25 questions that cover this topic on their own.
A phone book is stored as a list of (name, value) pairs. Write find(pairs, name) that scans from the front and returns (value, comparisons), with value = None on a miss. For n = 100, 400 and 1,600 seeded names, count the comparisons for a hit on every name and for a miss, and print the average hit cost beside n / 2. Then time 400 seeded hit lookups on n = 4,000 against a dict built from the same pairs, using best_of(fn, repeats=3) (min of 3 runs). Finish with one sentence: what would the key have to do for the lookup to skip the scan?
If the keys are small integers 0..m-1, a plain list is already a lookup table: table[key] is one step. Build one for 10 ids and show it works. Then ask what it costs when ids are up to 999,999,999: measure sys.getsizeof of a list with 10^3 slots and with 10^6 slots, print the ratio, and extrapolate to 10^9 slots in whole gigabytes. Finally shrink the key with id % 2048 for 1,000 seeded sparse ids and count how many ids end up sharing a slot.
A hash function turns any key into a number, and hash % m turns it into a bucket index. Write poly_hash(s, base=31, mod=2**61 - 1) using h = (h * base + ord(ch)) % mod, and sum_hash(s) that just adds the character codes. Print the bucket index of 12 words with m = 16 under both. Four of the words are anagrams of listen and four are anagrams of stone. Show that sum_hash puts every anagram in one bucket while poly_hash uses the order of the letters, and that poly_hash gives the same answer every time it is called.
Show that collisions cannot be avoided. First the pigeonhole version: put keys 0..8 into 8 buckets with key % 8 and print which bucket gets two. Then the birthday version: write p_collision(k, m), the exact probability that k random keys in m buckets have at least one shared bucket, and check it against a seeded simulation (10,000 trials) for (23, 365), (40, 365) and (40, 1024). Finally print the smallest k where the probability passes 1/2 for m = 365, 1,024 and 65,536, next to 1.1774 * sqrt(m).
Build HashMap with separate chaining. self.buckets is a list of m = 8 lists, each holding [key, value] pairs. _index(key) is self.hash_fn(key) % len(self.buckets), and the constructor takes hash_fn (default hash). Implement put, get(key, default=None), __contains__, __len__ and load_factor(). A put or get scans only the one chain its key maps to. Insert the int keys 3, 11, 19, 5, 13, 6, 0, 8 (for an int, hash(n) == n) and print the buckets so that 3, 11 and 19 are seen sharing bucket 3. This table does not resize yet. Fuzz it against a dict with 3,000 seeded operations.
Using the chaining HashMap (define it in your answer, with put, get, remove, __len__), show what goes wrong if put appends without checking for an existing key: put key 3 twice with different values on a buggy subclass and print the get result and the length beside the correct table. Then show that the buggy table's remove leaves a ghost behind. Finally show that the correct remove touches only one chain (print the buckets before and after), returns False for a missing key, and fuzz it against a dict.
The load factor is alpha = n / m, the average chain length. Build a fixed m = 1,024 chaining table with no resizing, fill it with seeded distinct random int keys until alpha is 0.5, 1, 2, 4 and 8, and measure at each step: the longest chain, the average comparisons for a hit (over every stored key) and for a miss (over 2,000 absent keys), and the time of 2,000 hit lookups with best_of(fn, repeats=3). Print one table, and conclude from those same numbers that the cost of one operation is about 1 + alpha.
Make the chaining HashMap grow: after an insert, if n / m > 0.75, double the bucket count and re-insert every key, because % m gives a different answer when m changes. Insert the int keys 3, 11, 19, 5, 13, 6 and print the buckets, then insert 14 and print them again so the resize is visible. Then show the tempting bug: doubling the list of buckets without re-inserting, and print get(11) beside the correct table. Fuzz the table against a dict and check that the load factor never exceeds 0.75 after a put.
A resize moves every stored key, so it looks expensive. Count the total number of key moves over n inserts of the ints 0..n-1 into a chaining table that starts at m = 8 and resizes whenever n > 0.75 * m, under two growth rules: double m, and add 8 to m. Use n = 500, 1,000, 2,000 and 4,000. Print the moves per insert, show that doubling stays under 2 per insert, and show from the same numbers that the +8 rule's cost per insert keeps growing. This is the dynamic-array argument from DSA Topics 1โ2 again.
Chaining is not the only way to handle a collision. Build ProbingMap: one flat list self.slots of None (empty) or (key, value) tuples. On a collision, try the next slot, wrapping around the end. put and get record how many slots they inspected in self.probes. The constructor takes m=8, hash_fn=hash, and a grow flag. With grow=True it doubles when n / m > 0.75; this version has no remove yet. Insert 3, 11, 19, 4, 12, 15 and print the slot array and each put's probe count, including a wrap-around. Look up a missing key and print its probes. Then fill a grow=False table completely and show that a miss on a full table only stops because of a probe cap. Fuzz against a dict.
Linear probing has a weakness: filled slots form runs, and a key that hashes into a run must walk to its end, which makes the run longer still. Build a ProbingMap with m = 4096 slots, no resizing and no removal, and fill it with seeded random int keys to load factors 0.5, 0.7, 0.8, 0.9 and 0.95. Average over 6 fresh tables per load factor. For each, measure the average probes (slots inspected) of a hit and of a miss, and the longest run of filled slots. Compare with Knuth's estimates: a hit costs (1 + 1/(1 - a)) / 2 and a miss costs (1 + 1/(1 - a)^2) / 2. Also print what a miss would cost if every probe landed on an independent random slot (1 / (1 - a)), to show that the clustering is the extra cost. Check that every measurement is within 20% of Knuth.
A ProbingMap finds a key by walking until it meets an empty slot, so emptying a slot in the middle of a run cuts the chain. Add remove to the table in two ways: the naive way sets the slot back to None, and the right way writes a DELETED = object() tombstone, which get walks past and put reuses (first checking the rest of the run, so the key is not stored twice). With m = 8, insert 3, 11 and 19 (all hash to slot 3), remove 11, and print what get(19) returns under each version, then put 27 and show it takes the tombstone's slot. Since a tombstone still lengthens probes, the table counts n + tombstones toward its load factor and rebuilds when that passes 0.75. Fuzz both versions against a dict with 4,000 seeded operations (puts, removes and gets), counting any wrong answer or exception as a failure.
Run a chaining table and a linear-probing table on the same seeded workload: m = 2048 buckets or slots, n seeded random int keys with n / m = 0.5, 0.75 and 0.9, no resizing. Measure the average cells examined per hit and per miss (for chaining, the cells on the chain walked; for probing, the non-empty slots touched), and the memory of each structure with sys.getsizeof (the list plus its pairs or tuples; keys are shared, so they are left out). Then compare deletion: at alpha 0.75, delete two thirds of the keys and measure the miss cost again. The probing table has to leave tombstones; also measure a probing table rebuilt from the survivors. Print theory beside each measurement, and state that CPython's dict and set use open addressing, as an implementation detail.
Explore the built-in hash() and print only what is the same on every machine and every run. Show that hash(n) == n for small ints, that hash(-1) == -2 (and so hash(-1) == hash(-2), because the C code reserves -1 as an error value), that ints hash modulo sys.hash_info.modulus, and that 1, 1.0 and True hash alike because they compare equal, so they are one dict key. Show that a tuple's hash is built from its items (the same items give the same hash, a different order or item gives a different one), and that equal frozensets hash alike whatever the insertion order. For strings, explain in a comment why hash("abc") is salted per process, and print only comparisons: equal strings built different ways hash alike inside one run. Never print a raw string hash. Finally turn a hash into a bucket with % 8 and show that Python's % keeps negative hashes in range.
Show why lists are refused as dict keys. STEP 1: try {[1, 2]: "x"} and hash([1, 2]), catch the TypeError and print its type and message. STEP 2: build a minimal chaining HashMap (m = 8, hash_fn argument, put, get, __len__) and give it hash_fn = lambda key: hash(tuple(key)), so a list is hashed by its contents. Put [1, 2] in. STEP 3: mutate that same list by appending the first value that moves its content hash to a different bucket, then show that get misses a key that is still in the table (print the two bucket indexes, the length, and the miss). STEP 4: explain in a print what the table did wrong, and fix it with a tuple key: show that a tuple cannot be mutated, and that the lookup works.
Use compound keys. Store a small sparse grid as a dict from (row, col) tuples to letters, and count the stored neighbours of a cell by looking up its eight surrounding tuples. Then take 1,000 seeded road pairs (a, b) between cities 0..59 where (a, b) and (b, a) are the same road: count the distinct roads with plain tuples (which treat the two orders as different), with a frozenset per road, and with an oracle that stores (min, max). The frozenset count must match the oracle. Show that a set cannot be a key but a frozenset can, and that a tuple holding a list is still unhashable (catch and print the error).
Make your own class usable as a key. STEP 1: a plain Point(x, y) class: build two points with the same coordinates and show that a set holds both, because the default equality and hash use identity. STEP 2: add __eq__ (comparing x and y, returning NotImplemented for other types) and __hash__ returning hash((self.x, self.y)); show that the set now holds one point and that a dict lookup with a fresh equal point works. STEP 3: state the contract, a == b must imply hash(a) == hash(b), and write a function that checks it for every pair in a seeded list of 200 points. The converse is not required: print how many unequal pairs share a hash anyway (collisions are legal). STEP 4: show that a class defining __eq__ alone becomes unhashable (its __hash__ is None). STEP 5: @dataclass(frozen=True) writes both methods; show it, and show that mutating a frozen instance raises FrozenInstanceError.
Compare four string hashes on 2,000 seeded words (1,000 random lowercase words of length 4โ9 and 1,000 similar ids item0000โitem0999) put into 1,024 buckets: len(s), the first letter's ord, the sum of the ords, and the polynomial poly_hash(s, base=31, mod=2**61 - 1) (h = (h * base + ord(ch)) % mod). For each print the empty buckets, the longest chain, and the average chain length a key sits in (sum(c*c) / n; random placement gives about 1 + (n - 1) / m). Then test the two properties a good hash needs besides spreading: it uses every character (change one middle character and see whether the hash value moves) and it uses their order (swap two neighbouring different characters). Print the share of words whose hash value did not change for each hash, and conclude from the numbers.
Make the chain visible. STEP 1: build a HashMap (chaining, m = 8, doubling when n / m > 0.75, hash_fn=hash) and two key classes that share an __eq__ which counts its calls: GoodKey(v) hashes to v, and BadKey(v) hashes to the constant 42. STEP 2: insert n keys for n = 250, 500, 1,000 and 2,000, then look up one absent key. Print, for both classes, the __eq__ calls for the inserts and for the miss (for BadKey they must be exactly n(n-1)/2 and n), plus the best-of-3 insert time. STEP 3: from the same table, conclude in words: average O(1), worst O(n) per operation, so n inserts cost O(n^2) in the worst case. DSA Topic 1 timed this same key inside dict; here you can count the chain.
Measure x in list (O(n)) against x in set (O(1) on average) for n = 1,000, 4,000 and 16,000 seeded values, with 200 random probes drawn from 0..2n - 1 (about half are hits). Take best-of-3 for the whole batch of probes on the list, on the set, and for building the set from the list. Print the per-lookup times, the build cost, and the break-even: the number of lookups after which build + k * t_set is smaller than k * t_list. Then, from the same numbers, print the total cost of k = 1, 5 and 50 lookups both ways. State the rule and the complexity of building a set (O(n)), and note that a set pays off after very few lookups.
Remove duplicates from a list of 4,000 seeded words and keep each word's first-seen position. Write three versions: dedupe_seen (a seen set and an output list), dedupe_fromkeys (list(dict.fromkeys(items))) and dedupe_quadratic (if x not in out). Check that all three agree, then time them with best_of(fn, repeats=3) (min of 3 runs) and print the quadratic version's ratio to the set version. Also show that list(set(items)) has the same members but no promised order: for strings the order changes between runs, so only print it sorted. Show one small int example where list(set(...)) visibly reorders.
Ask five containers for a key that is not there and record what each does: d[k], d.get(k, 0), d.setdefault(k, []), a defaultdict(list) read, and a Counter read. For each, print what comes back (or the exception) and whether len grew. Then use them in the job they suit: group three words by first letter with setdefault, with defaultdict(list), and count letters with Counter, and check that all three groupings agree.
A dict remembers insertion order, and since Python 3.7 that is a language guarantee (CPython's compact layout stores entries in an array in the order they arrived). Show three things with a dict of five keys: overwriting a key keeps its position, deleting a key and inserting it again moves it to the end, and two dicts with the same items in a different order are still ==. Then show that a set promises no order: build {8, 0} and {0, 8} with add, print how each iterates, and check they are equal anyway.
Time your own chaining HashMap against dict on the same work. Define a HashMap that resizes at load factor 0.75 (m starts at 8, put, get, __len__). Run 50,000 seeded puts and then 50,000 seeded gets with string keys on both, check the two agree on every answer, and print each total with best_of(fn, repeats=3) and the ratio. Then explain the gap with one measurement: a fresh 1,000,000-character string takes real time to hash the first time, and almost none the second, because a str caches its hash. Finish by saying when you would still write your own table.
Ten requirements arrive, and each one is decided by a single property: exact membership, exact lookup of a value, counting, grouping items that are not hashable, a range, or the nearest value. Write a PROPERTY_TO_TOOL table that maps each property to set, dict, Counter, sort + group or sorted + bisect, route the ten statements through it, and print the choices. Then back the two least obvious routes with a tiny demo: group lists (which cannot be keys) by sorting and walking runs, and find the nearest value to 50 with bisect.
Given a list of integers and a target, return the indices (i, j) with i < j and items[i] + items[j] == target, or None. Write two_sum(items, target) in one pass over a dict that maps value to index: for each x, look up target - x first, then store x. Show that [3, 3] with target 6 works, then show the one-element-used-twice bug when you store first and look up second (print it on [3, 2, 4] with target 6). Check the fix against a double loop on 400 seeded cases, with exceptions counted as failures. DSA Topic 4 already solved two-sum on a sorted list with two pointers: compare the two on memory and on what they require.
Count the index pairs i < j with items[i] + items[j] == k. Duplicates multiply: [2, 2, 2, 2] with k = 4 has 6 pairs, not 1. Write count_pairs(items, k) with a Counter of earlier values: for each x, add seen[k - x] to the answer and only then count x. Show what happens when you count x first (print it on [2, 2, 2, 2]), and fuzz the fix against the O(n^2) double loop on 500 seeded lists with exceptions counted as failures.
Three counting problems are one template. Write count_pairs(items, partners, key): for each x, add seen[p] for every p in partners(x), then do seen[key(x)] += 1. Instantiate it three ways and fuzz each against a double loop. (a) Pairs i < j with abs(items[i] - items[j]) == k; for k = 0 the pairs are repeats, so check that case. (b) Pairs with items[i] ^ items[j] == k. (c) Pairs with (items[i] + items[j]) % m == 0, where remainder r pairs with (m - r) % m. Use 400 seeded lists per variant, and count exceptions as failures.
Count how often each word appears in a 2,000-word seeded text three ways: dict.get(w, 0) + 1, defaultdict(int) and Counter. Check that all three give the same map. Then find the mode (the most frequent word) with an explicit tie-break, so that a tie goes to the alphabetically smaller word, and print a histogram sorted by (-count, word) with one # per 10 occurrences. Explain in comments why counting is O(n) on average, and show a case where an unsorted max over a dict picks the first-seen word and a different tie-break would pick another.
Return the k most frequent values of a list, most frequent first, with ties broken by the smaller value. Write top_k(items, k): build a Counter, then sorted(counts, key=lambda v: (-counts[v], v))[:k]. State the tie-break in a comment, check k larger than the distinct count, and fuzz against a selection oracle (repeatedly pick the best remaining value by hand) on 400 seeded lists with exceptions counted as failures. In comments, name the O(n) bucket-by-count idea as counting sort (DSA Topic 9) and the O(n log k) heap idea as DSA Topic 15; build neither.
Find the index of the first character of a string that appears exactly once, or -1. Write first_unique(s) with two passes: a Counter in the first, a left-to-right scan in the second. Show the s.count(ch) version first and time both on 4,000 random lowercase letters. Then handle a stream: FirstUniqueStream takes push(ch) one character at a time and first() must answer at any moment. Keep a dict of candidates in arrival order, delete a character on its second sighting, and remember it in a repeated set so a third sighting cannot re-add it. Print what happens on the stream "aaa" when you forget the repeated set. Fuzz both versions against the plain function on 300 seeded strings, counting exceptions as failures.
Can note be built from the letters of magazine, using each magazine letter at most once? Write three versions of can_build(note, magazine): Counter subtraction (Counter(note) - Counter(magazine) must be empty), a 26-slot list of counts, and sorting both strings and walking them together. Show the tempting set-based check set(note) <= set(magazine) and print an input where it says yes and the truth is no. Fuzz all three against a list.remove oracle on 400 seeded cases, with exceptions counted as failures. Time the three on a 100,000-letter note and a 300,000-letter magazine, and print the timings with the ratio to the fastest.
Group words that are anagrams of each other. The whole problem is the choice of key: two words belong together exactly when their keys are equal. Write group_by_key(words, key) using a dict of lists, then try three keys. The sorted key is ''.join(sorted(word)), which costs O(k log k) per word of length k. The count-tuple key is a tuple of 26 letter counts, which costs O(k) when built with a loop over the characters. A third key builds the same tuple with word.count(letter) for each of the 26 letters. Print the groups of a small word list with each group sorted and the groups sorted. Show the wrong key sum(map(ord, word)) merging words that are not anagrams. Check that all three correct keys produce the same partition, then time them on 200 words of length 3,000 built from 20 shuffled families, and print the timings with ratios. Say what the timings show, from the printed numbers.
Grouping is one idea with many keys: defaultdict(list), then groups[key(item)].append(item). Write group_by(items, key) and use it to group 12 words by length and 20,000 seeded records (name, dept, year) by the tuple (dept, year). Compare with the sort-then-group approach, sorted(items, key=key) followed by itertools.groupby, which needs the sort first. Show what groupby does without the sort (print the fragments on [3, 1, 3]). Check that the two approaches give the same groups on the records, then time both.
Two strings s and t of equal length are isomorphic when every character of s can be replaced by exactly one character of t, and no two different characters of s map to the same character of t (a bijection). Write isomorphic(s, t) with two dicts, s -> t and t -> s. Then write the one-map version a student would try first, and print both on ("ab", "aa") beside the truth. Use an independent oracle: the strings are isomorphic exactly when len(set(zip(s, t))) == len(set(s)) == len(set(t)). Fuzz the two-map version and the one-map version on 500 seeded pairs, counting exceptions as failures, and print how many pairs the one-map version gets wrong.
Given a pattern such as "abba" and a sentence such as "dog cat cat dog", decide whether the sentence follows the pattern: each pattern letter stands for one word, and different letters stand for different words. This is the bijection from the previous problem over words. Write word_pattern(pattern, sentence). Split first and compare the lengths before anything else. Show what zip does when you skip the length check (it stops at the shorter side), printing an input the buggy version accepts. Fuzz against the oracle len(set(zip(p, w))) == len(set(p)) == len(set(w)) (plus equal lengths) on 400 seeded cases, counting exceptions as failures.
Given an unsorted list of integers, return the length of the longest run of consecutive values (such as 4, 5, 6, 7), in O(n) time. Put the values in a set, and start counting only at a value x where x - 1 is absent, because only the start of a run should walk it. STEP 1: write longest_run(items), counting the inner while steps. STEP 2: write the version that starts counting at every value, and print the step counts of both on 2,000 consecutive integers in shuffled order. STEP 3: prove in a comment why the guarded version takes at most n inner steps in total. STEP 4: write the sort-and-scan version, fuzz all three against a brute force on 400 seeded cases (exceptions count as failures), and time the set version against sort-and-scan on 200,000 values. Union-find (DSA Topic 18) solves this with merging; name it in a comment and do not build it.
Is there a pair of positions i != j with items[i] == items[j] and abs(i - j) <= k? Write repeats_within(items, k) in one pass with a dict that maps each value to the last index where it was seen. Show why the dict must be updated to the latest index every time: print what happens on [1, 0, 1, 1] with k = 1 when the dict keeps the first index instead. Check the edge case k = 0 (never true, because i != j needs a gap of at least 1). Fuzz against the double loop on 500 seeded cases, counting exceptions as failures.
Two lists of ids, A and B, with no repeats inside each. STEP 1: write four functions with nested loops (or in on a list) that return the ids in both, in either, only in A, and in exactly one. STEP 2: write the same four with the set operators &, |, - and ^, and check that the results agree after sorting. STEP 3: time both on lists of 1,000 ids, and print the two timings and the ratio. STEP 4: show that a & b iterates the smaller set: time small & big (100 against 500,000 ids) against big & big2 (500,000 against 500,000) and print the ratio. Put the costs in comments: the nested loops are O(n * m), the operators are O(n + m), and a & b is O(min(len(a), len(b))) on average.
The intersection of two lists as multisets keeps how many times each element is common: [1, 2, 2, 3] and [2, 2, 2, 5] share two 2s. Show set(a) & set(b) losing the count, and Counter(a) & Counter(b), which keeps the minimum count of each element. Print both on one input, and again on a list of words, with the output sorted. Write common_elements(a, b) that returns the shared elements as a sorted list with multiplicity. Fuzz it against a list.remove oracle on 400 seeded cases (exceptions count as failures). Then note that Counter(a) | Counter(b) is the multiset union (the maximum), and print it.
A list of records, each a dict such as {"name": "Ada", "city": "Oslo", "ts": 10}, has duplicates: two records are the same person when their name and city match, whatever the ts. A dict is unhashable, so set(records) fails. Dedupe by a chosen key tuple instead, and keep first-seen order. Write dedupe_first (keep the first record per key, with a seen-set), dedupe_last_in_place (keep the last record, but at the position where the key first appeared: assigning to an existing dict key keeps its position), and dedupe_last_moved (keep the last record, ordered by last appearance: pop the key, then insert it again). Write dedupe_truth with plain list scans for all three modes, and dedupe_whole_record, which keys on every field and so never merges two records that differ in ts. Show the TypeError, run the example, and fuzz 2,000 seeded lists.
DSA Topic 6 counted subarrays with sum k using a running prefix and a dict of how often each prefix has appeared. Here the pattern is fixed, and the store is what changes. Count the subarrays with the same loop over four stores: (1) a list of [prefix, count] pairs searched linearly, (2) a sorted list of prefixes kept with bisect.insort, where the count of a value is bisect_right - bisect_left, (3) a hand-built chaining HashMap (m starts at 8, doubles when the load passes 0.75, counts its key comparisons), and (4) a dict. Check them against an O(n^2) truth on 300 seeded arrays. Time all four at n = 3,000 and the last three at n = 30,000 with best_of(fn, repeats=3). Then show when the O(1) average fails: the same table with a hash function that returns 0 for every key makes one long chain, and the comparison counts say so. Finish by saying what a dict cannot answer.
A list of dominoes [a, b] is given. Dominoes [a, b] and [c, d] are equivalent when a == c and b == d, or a == d and b == c: a domino can be turned around. Count the pairs i < j of equivalent dominoes. Use a canonical key (min(a, b), max(a, b)), a Counter over the keys, and add c * (c - 1) // 2 for each count c. Write equiv_truth (a double loop), equiv_pairs, equiv_ordered (the key is (a, b) as given, so a turned domino is a different key) and equiv_ordered_pairs (counts c * (c - 1), ordered pairs). Print an example, then fuzz 2,000 seeded lists, catching exceptions as failures.
A happy number is one where repeatedly replacing n by the sum of the squares of its digits reaches 1; every other number falls into a cycle and never does. Detect the cycle with a seen-set: stop at 1, or when a value repeats. Write is_happy_set, is_happy_floyd (the tortoise and hare from DSA Topic 4, with O(1) memory), is_happy_truth (every unhappy number is known to reach 4, so iterate until 1 or 4) and is_happy_capped, which gives up after 5 steps instead of tracking repeats. Compare them for n in 1..10,000. Then compare memory on a longer walk, f(x) = (x * x + 1) % 1000003 from 2: find the first repeated value with a set and with Floyd, and print tracemalloc peaks and the number of f calls each used.
A 9 x 9 board is a list of 9 strings of digits 1-9 and . for blank. It is valid so far when no digit repeats within a row, a column or a 3 x 3 box. Scan the cells in row-major order with a set per row, a set per column and a set per box, keyed by (r // 3, c // 3), and report the first conflict as (row, col, kind, digit), checking row, then column, then box for that cell; return None when there is none. Write first_conflict_truth (compares each cell with every earlier cell), first_conflict, and first_conflict_bad_box, whose box key is r // 3 + c // 3. Build a valid full board with a formula, try single edits, then fuzz 3,000 seeded boards.
Four lists A, B, C, D of the same length n are given. Count the index tuples (i, j, k, l) with A[i] + B[j] + C[k] + D[l] == 0. Trying every tuple is O(n^4). Meet in the middle: build a Counter of every A[i] + B[j] (n^2 sums), then for every C[k] + D[l] add the count stored for its negative. That is O(n^2) time and O(n^2) space. Write four_truth (four loops), four_sum, four_wrong_sign (probes with c + d) and four_set (a set of sums, which loses multiplicity). Check the example A=[-1,-1], B=[2,-1], C=[0,0], D=[2,2], fuzz 500 seeded cases (n up to 8), and time n = 10, 20, 40 for both with best_of(fn, repeats=3).
Many addresses reach the same mailbox. Under the rules for this service, the local part (before @) ignores every . and everything from the first + onward, and the domain (after @) is case-insensitive. The local part keeps its letter case, and the dots in the domain stay. Count the distinct mailboxes in a list of addresses. The key is the canonical form: normalise each address, then put it in a set. Write canonical, count_mailboxes, and two wrong versions: canonical_dots_everywhere, which strips dots from the whole address, and canonical_case_sensitive_domain, which forgets to lowercase the domain. Check a hand-counted example, then fuzz 1,000 seeded lists built from known mailboxes.
In the game, a secret and a guess are digit strings of the same length (digits may repeat). A bull is a position where the two strings have the same digit. A cow is a digit of the guess that is in the secret but at a different position, and each digit of the secret can be used once. Report "xAyB" for x bulls and y cows. Count the bulls by position, put the unmatched digits of each side in a Counter, and the cows are the sum of the values of Counter & Counter, the multiset intersection. Write bulls_cows_truth (delete matched digits from a list), bulls_cows, bulls_cows_set (intersects the sets of leftover digits) and bulls_cows_reuse (lets a secret digit match several guess digits). Print the classic examples and fuzz 3,000 seeded pairs.
Given n distinct points (x, y), find the most points that lie on one straight line. For each anchor point, key every other point by the reduced direction (dy // g, dx // g) with g = gcd(|dy|, |dx|), and a sign rule so that opposite directions match: make dx positive, and when dx == 0 make dy equal to 1. The most common direction plus the anchor itself is the best line through that anchor. Write max_line_truth (the cross product test for every triple), max_line, and three wrong versions: max_line_no_gcd, max_line_first_anchor (tries only the first point as anchor) and max_line_float, which keys on dy / dx. Fuzz 1,500 seeded sets on a small grid, then show a case with large coordinates where two different slopes round to the same float.
Ten requirements arrive in plain words. Each one is a few yes/no features: does it ask about order (a range or the nearest value), a contiguous sum, a pair, a group, a count, or a value looked up by key? Write route(features), a short decision list that returns one of set, dict index, Counter, group-by, complement map, prefix + dict or sorted + bisect. Route all ten statements through it, run each one with the tool it chose on a tiny input, and compare with a plain-loop answer. Several statements carry two features, so the order of the list decides the route. Print a table with a features column, and finish by naming the one question a hash table cannot answer.
A hash map answers "are these two things the same?" with == on the key, so the whole design problem is choosing a key that is equal exactly when the two things are equal for your problem. A key that is equal too often merges groups that should be apart. A key that is equal too rarely splits one group into pieces. Write partition(items, key) (a dict of lists, returning the groups sorted) and partition_truth(items, equal) (an O(n * g) pairwise oracle that never uses a key). Then design four keys and test each one against its own definition of "equal":
- A multiset of letters (anagrams: order is ignored, counts matter). Right key: a tuple of
(letter, count)pairs, sorted. Wrong key:frozenset(word), which ignores counts. - A multiset of numbers. Right key: the sorted tuple. Wrong key: the sum, which makes
(1, 4)and(2, 3)one group. - A set of numbers (order and repeats are both ignored). Right key:
frozenset. Wrong key: the sorted tuple, which keeps repeats. - A shape of grid cells, equal when one can be slid onto the other (no turning or flipping). Right key: subtract the smallest row and the smallest column from every cell, then sort. Wrong keys: the sorted cells without sliding, and the number of cells.
For each, print the groups for the right key and for the wrong key, say whether each one matches the oracle, and say from the group counts whether a wrong key merged groups or split them.
Two lowercase strings belong to one group when shifting every letter of the first by the same amount, wrapping from z to a, gives the second. So "abc", "bcd", "xyz" and "yza" are one group, and so are "az" and "ba". Find a key that is equal for exactly those strings: the tuple of (ord(b) - ord(a)) % 26 between neighbouring letters is shift-proof, and its length separates different lengths. Write shift_key, a second key that rotates the first letter to 'a' (first_to_a), and a brute-force shifted_equal that tries all 26 shifts. Print the groups of a small list. Then show the tempting key without % 26, which splits "az" from "ba". Fuzz on 300 batches of 25 random strings over the letters a b y z, comparing both good keys with the pairwise oracle and counting exceptions as failures, and print how many batches the no-modulo key got wrong.
Two strings are the same necklace when one is a rotation of the other ("aabb" and "abba"), and a hash map needs one canonical string per necklace. Write min_rotation(s), which builds every rotation and keeps the smallest, O(k^2) per string of length k, and group a list of necklaces with it. Verify pairs with rotations_equal(a, b): len(a) == len(b) and b in a + a. Show what happens when the length check is dropped, and show the wrong key ''.join(sorted(s)), which merges "aabb" with "abab". Fuzz the key against the pairwise check over 40 batches of 40 random strings from a b (length 0 to 6), counting exceptions as failures. Then time min_rotation on its own at k = 500 and k = 16,000, and time one rotations_equal call on its own at k = 16,000. Print the growth exponent of the key, log(t_big / t_small) / log(32), where 1 means linear and 2 quadratic, and the ratio of key cost to check cost. Name Booth's algorithm as the O(k) way to find the canonical rotation, without building it.
A cache of capacity c keeps the c most recently used entries. get(key) returns the value or -1, and counts as a use. put(key, value) also counts as a use, and when the cache is full it evicts the least recently used key. A dict remembers insertion order, so recency can live in the order: the oldest key is first and the newest is last. Build three versions and compare them. ListLRU is the O(n) reference, a list of pairs. DictLRU uses a plain dict: get pops the key and inserts it again at the end, and put evicts next(iter(self.d)). OrderedLRU uses collections.OrderedDict with move_to_end and popitem(last=False). Do not import functools. Each class has a keys() method listing keys from least to most recent.
Show the classic bug as a fourth class: a cache whose get does not refresh recency is a FIFO queue, so print a short trace where it evicts a key that was just read. Fuzz the three real versions against each other on 300 seeded operation sequences (capacity 1 to 4, keys 0 to 5, 40 operations), comparing every return value and the key order after every step, and counting exceptions as failures. Then measure whether eviction is really O(1): put 60,000 fresh keys into DictLRU and OrderedLRU at capacity 100 and at capacity 10,000, and print nanoseconds per put, each timed on its own. Say from the printed ratios which version stays flat.
The textbook version, a doubly linked list plus a map, is DSA Topic 12.
DSA Topic 5 built the RabinโKarp fingerprint, a hash of every window of a text that updates in O(1) as the window slides. Here the question is how often two different windows get the same fingerprint, and what modulus to choose. Write window_hashes(text, w, base, mod) with the rolling update. On a seeded DNA text of 200,000 letters (ACGT) with windows of 16 letters, do two things for the moduli 2**8, 2**16 and 2**31 - 1.
First, count colliding pairs: pairs of different window strings with equal fingerprints. Group the distinct windows by fingerprint, add up c * (c - 1) // 2 per group, and compare with the birthday estimate D * (D - 1) / (2 * M) for D distinct windows and modulus M. Second, run the RabinโKarp test for 20 patterns taken from the text: an index from fingerprint to positions, every candidate checked by direct comparison, and the false hits counted. Compare the false hits with the expectation 20 * (N - 1) / M for N windows, and check that the confirmed matches equal what str.find finds.
Then use a pair of fingerprints (two moduli, two bases) as the key and count again for the moduli (251, 241) and (2**31 - 1, 10**9 + 7). Print one table, and conclude from the printed numbers whether the birthday estimate is within a factor of 2 for the first two single moduli, and what the pair of big moduli does.
Eight prison cells, each occupied (1) or empty (0). Each day a cell becomes occupied if both its neighbours were the same on the previous day (both occupied or both empty), otherwise it becomes empty. The two end cells have only one neighbour, so they are empty after day 1. What do the cells look like after 1,000,000,000 days? The state is one of at most 256 tuples, so it must repeat. Write step(cells), then find_cycle_dict(start, f): walk forward and store each state's first day in a dict, and when a state repeats you know the cycle start mu and the cycle length lam, so day N is history[mu + (N - mu) % lam] for N past the start. Write find_cycle_floyd too (Floyd's tortoise and hare from DSA Topic 4), which keeps O(1) states instead of a dict. Fuzz both against plain simulation on 300 seeded starts and days up to 3,000, counting exceptions as failures. Show the tempting shortcut history[N % lam], which ignores the pre-cycle days, beside the truth for N = 10^9. Count the calls of step each method makes, and print the number of states each one keeps. Time simulation for 50,000 days and extrapolate to 10^9.
Design a service with add(x), which stores a number, and find(total), which says whether two different stored items (the same value twice counts, if it was added twice) sum to total. There are two designs, and the right one depends on how often each method is called. CountService keeps a dict of value to count: add is O(1) on average, and find scans the distinct values and looks up the complement, O(d). SumSetService keeps a set of every pair sum: add pairs the new value with every distinct stored value, O(d), and find is one set lookup, O(1). Show the bug in find that forgets a value cannot pair with itself unless it was added twice, beside a brute-force truth. Fuzz both services on 200 seeded operation sequences, with exceptions counted as failures.
Then measure on 800 distinct values: the cost of one add and one find (a miss, which is the worst case for the scanning design) for each design, each timed on its own, and compute the break-even number of finds per add, (addB - addA) / (findA - findB). Time two whole workloads of 800 adds, one with 20 finds and one with 8,000 finds, and print which design is faster for each. Say from the printed numbers whether both workloads sit far from the break-even.
Design RandomizedSet with insert(v) (False if present), remove(v) (False if absent) and get_random() (each stored value equally likely), all O(1) on average. A set cannot draw a random element without a scan, and a list cannot delete from the middle in O(1). Combine them: a list vals of the values, and a dict pos from value to its index in the list. To remove a value, overwrite its slot with the last element, fix that element's index in pos, and pop the tail. Pass a random.Random(7) into the constructor, so draws are reproducible. Show the bug that forgets to update the moved element's index (print what happens after insert 1, 2, 3; remove 1; remove 3). Fuzz against a plain set on 3,000 seeded operations over the values 0 to 9, checking after every step that the contents match and that pos[vals[i]] == i for every i, counting exceptions as failures. Draw 60,000 times from a set of 5 values and check each frequency lies within 5 standard deviations of the expected 12,000. Time a build-and-remove-everything run of 4,000 values against a version whose remove uses list.remove.
A hash table answers "is this exact key here?" and nothing about order. Four queries need order: count the keys in [lo, hi], list them in sorted order, find the key nearest to x, and find the words that start with a prefix. With a dict, each is a scan of all n keys. A sorted list plus bisect (DSA Topic 3) answers each in O(log n), plus the size of the output. Write both versions of each query on 20,000 distinct seeded integers (and 20,000 seeded 6-letter words for the prefix): count_range, list_range, nearest (the smaller key wins a tie) and with_prefix (use bisect_left(words, prefix + chr(0x10FFFF)) as the end of the prefix block). Fuzz the two versions against each other on 500 seeded queries per kind over a small universe, with exceptions counted as failures.
Time 100 queries of each kind with both structures, each timed on its own, and print the ratios. Then time 20,000 exact lookups in both and say which wins. Say from the printed numbers whether the sorted list won every ordered query. Finish in a comment: inserting into a sorted list is O(n), so a changing set of keys wants a tree (DSA Topic 14), and prefixes want a trie (DSA Topic 16).
A Bloom filter answers "have I seen this?" in far less memory than a set, by being allowed to be wrong in one direction: it may say yes for something it never saw (a false positive), and it never says no for something it did see. It is a bit array of m bits and k positions per item. Build Bloom(m_bits, k) on a bytearray with add and in. Derive the k positions from two polynomial hashes of your own, h1 = poly_hash(s, 31) and h2 = poly_hash(s, 131) | 1, as (h1 + i * h2) % m (use m = 2**15, a power of two, so an odd h2 visits distinct positions). Insert 5,000 seeded random 10-letter strings and test 50,000 other random strings. Check that no inserted string is missed, then print, for k in 1, 2, 4, 6 and 10, the measured false-positive rate against (1 - e^(-k * n / m))^k, and say whether every measured rate is within 20 percent of the formula. Show why a Bloom filter cannot delete: clear the bits of 500 inserted strings and count the other inserted strings that now test absent. Compare the memory with sys.getsizeof of the bit array, of a set of the same strings, and of the strings themselves, and note that getsizeof is shallow.
You run N cache servers and send each key to one of them. The obvious rule is servers[h(key) % N]. Add one server and % N becomes % (N + 1), so nearly every key changes owner and nearly every cached value is lost. A hash ring fixes that: hash each server to many points on a circle (here 100 virtual nodes per server, so the load evens out), keep the points in a sorted list, and give a key to the first point at or after its own hash, wrapping past the end (bisect, DSA Topic 3). Hash with stable(s) = mix(poly_hash(s)), where poly_hash is the topic's polynomial hash and mix is a 64-bit finaliser, because similar names such as srv1#7 and srv1#8 otherwise land next to each other. On 20,000 seeded keys: count how many keys change owner when an 8-server cluster becomes 9 servers under modulo and under the ring, check that every key the ring moves goes to the new server, remove a server and check that only its keys move, and compare the load spread (largest load / smallest load) for 1 virtual node against 100.
How much memory does a hash table cost per entry? Use sys.getsizeof and let the ratios carry the conclusion, because the byte counts change between Python versions. Write the answer in four steps. (1) Grow a list, a dict and a set one element at a time to 20,000 integers and record every size at which getsizeof changes: those jumps are the resizes. Print how many jumps each container has and the average growth factor between neighbouring jump points. (2) Bytes per entry (shallow) at n = 1,000, 10,000 and 100,000. (3) getsizeof is shallow: add the size of the keys themselves for 100,000 ints and for 100,000 ten-character strings, and print the shallow and deep bytes per entry. (4) A bytearray bitmap against a set for 50,000 distinct integers drawn from a universe of 100,000: print both sizes and the density at which the bitmap stops winning, and fuzz the bitmap against the set.
A vector with 100,000 dimensions and 100 non-zero entries is mostly zeros. Store only the non-zeros as a dict from index to value. The dot product then loops over the smaller dict and looks each index up in the other, so it costs O(min(nnz_a, nnz_b)) on average instead of O(dimension). Write dot_dense (zip of two lists), dot_sparse (iterate the smaller dict), and dot_sparse_big_first, which iterates the larger dict on purpose. Fuzz dot_sparse against dot_dense on 500 seeded small vectors, and check that no stored entry is zero. Then at 100,000 dimensions and densities 0.001, 0.01, 0.1 and 0.5, time each dot product and print the ratio dense / sparse, and print the memory of both layouts, with the keys counted. From the measured bytes per sparse entry, compute the density below which the dict is smaller. Finally take one sparse vector (density 0.001) and one dense one (density 0.5) and time the two loop orders.
Two words are neighbours when they have the same length and differ in exactly one position. To find every neighbour pair among n words of length k, comparing all pairs costs O(n^2 * k). Index instead: for each word make its k patterns by replacing one letter with '*' (so hat gives *at, h*t, ha*) and put the word in a bucket named by each pattern. Two words that differ in exactly one position share exactly one pattern, so every neighbour pair sits together in one bucket, and no pair is counted twice. Write pairs_scan (the all-pairs check), pairs_index (the bucket version) and pairs_truth (itertools.combinations, an independent third way). Use words of length 5 over the alphabet abcdef, drawn by a seeded sample. Fuzz the index against the truth on 200 small lists (duplicates included), count the patterns stored, time the scan at n = 400 and 800 and the index at n = 400, 800, 1,600 and 3,200 with best_of(fn, repeats=3), and say what a very large bucket does to the bound. (A breadth-first search over this neighbour graph is DSA Topic 17.)
A log of 100,000 lines each carries a host name, and there are only 50 distinct hosts. Reading the log creates a new string object for every line, so the same name is stored 2,000 times. Interning keeps one canonical object per value: a dict that maps each value to its first object (canon.setdefault(s, s) returns the stored object, and the new copy is freed), or sys.intern(s) for strings. Build the host column three ways (raw, a canonical dict, sys.intern) into a pre-sized list, measure the memory the strings use with tracemalloc (read the current traced size before and after filling the list, so the list's own memory is not counted), count distinct objects with id, and print the ratios. Then show is against ==: equal strings are == always, but is is true only when they are the same object, so is is a fast path after interning and never a replacement for ==. State the cost of the canonical dict.
Find every pair of points at distance at most d among n points with integer coordinates. All pairs is O(n^2). Spatial hashing buckets each point by its cell (x // d, y // d): two points within d of each other lie in the same cell or in two of the 9 cells around it, so each point only checks the 9 cells' occupants, O(n + pairs) expected when the points are spread out. Use // on integers, never a float: show 0.3 // 0.1 giving 2.0, which puts a point in the wrong cell. Write close_pairs_truth (all pairs, squared distance <= d * d), close_pairs_grid, and two broken grids a student might write: own_cell_only (checks only the point's own cell) and cross_only (checks the cell and its 4 side neighbours but skips the diagonals). Negative coordinates are allowed. Fuzz on 300 seeded small inputs, catching exceptions as failures, print the broken versions' counts beside the truth on one input, and time the truth and the grid at n = 2,000 and the grid alone at n = 20,000.
An n by n grid has n rows and n columns. Count the pairs (r, c) such that row r equals column c, read as sequences of n numbers. Comparing every row with every column is O(n^3). Instead, make a Counter of the rows as tuples (a list is unhashable), then for each column look up its tuple: the answer adds the count of rows equal to it, so duplicate rows count once per matching row. Write count_brute (which also counts the cell comparisons it makes), count_counter, and two broken versions: count_set (a set of rows, so identical rows collapse and the count is too small) and count_sums (compares row sum with column sum, which merges different sequences). Show the TypeError for a list key, fuzz on 500 seeded grids with exceptions counted as failures, print the cell comparisons for the all-zero grid (the worst case, exactly n^3), then time brute and counter on a mostly-zero 100 by 100 grid and the counter alone at n = 300.
Two record lists share a join key: orders (order_id, customer) and tickets (ticket_id, customer). A join returns (order_id, ticket_id, customer) for every pair with equal customers, and a customer who has 3 orders and 4 tickets produces 12 rows (many-to-many). The nested-loop join compares all n * m pairs. The hash join builds a dict from key to the list of records on the smaller side, then probes it once per record on the other side: O(n + m + output) expected. Write join_nested, join_hash (build on the smaller side, return the rows in the orientation (left id, right id, key), and also return how many records the table holds), and join_overwrite, a broken version whose dict keeps one record per key. Fuzz on 500 seeded inputs (empty sides included, exceptions counted as failures), show the broken version's row count beside the truth, show that building on the smaller side stores fewer records, time both joins at n = m = 1,500 with 400 distinct customers, and say what the bound becomes when every record has the same key.
Java's String.hashCode is h = 31 * h + ord(c), wrapped to 32 bits. Two different strings give the same value: "Aa" and "BB", because 65 * 31 + 97 == 66 * 31 + 66. The hash is a polynomial, so if every block is replaced by the other one, the total is unchanged. Concatenating k blocks, each either "Aa" or "BB", therefore gives 2^k distinct strings with one hash value. Write java_hash and family(k), and check that the family has 2^k members and one hash value. Insert the family into the hand-built chaining table (m starts at 8, doubles when the load passes 0.75) using java_hash, counting every key comparison during put: it is exactly n * (n - 1) / 2, the quadratic worst case. Compare with the same number of random strings of the same length under the same hash, show that Python's own hash still tells the family apart, and time the two inserts for k = 6 to 10. An attacker who knows an unsalted hash can send a request full of such keys; the defence is a salted hash.
Eight workloads, one structure each. Write route(w), where w is a dict of properties (exact, ordered, counts, dense_ints, approx_ok, lookups, q_star) and the result is one of set, dict, Counter, sorted + bisect, bitmap, Bloom filter, plain list. Route all eight and assert that each choice matches the expected one. Then measure the break-evens behind the rule: (1) build cost against per-lookup savings for list versus set at several sizes, giving q* = build / (list lookup - set lookup), the number of lookups above which building the set pays; (2) counting keys in a range with a dict scan against sorted + bisect; (3) memory of a bitmap against a set for a dense integer universe; (4) memory of a Bloom filter with 10 bits per item against a set. Time each piece on its own, never by subtracting two minimums, and let the verdicts follow from the printed numbers.
A Seat class defines __eq__ and __hash__ from its row and col fields, and both fields can be changed. Store Seat(3, 4) in a dict, then set its col to 5. Print the dict's keys, s in booked, Seat(3, 4) in booked and s in list(booked), and explain each answer. Then store booked[s] again and show that the dict now holds two keys that are the same object. Next, show that the bug is intermittent. Put 1,000 seats in a dict, then 1,000 times mutate a seeded random seat, check whether it is still found, and put it back. Count how often the lookup succeeds by luck. Finish with two fixes: a @dataclass(frozen=True) seat that refuses mutation, and a class that hashes and compares only an id that never changes.
Write three point classes. EqOnly defines __eq__ and no __hash__, HashOnly defines __hash__ and no __eq__, and Both defines both from the same fields. Show what each does in a set. EqOnly raises a TypeError (catch it, and print that its __hash__ is None). HashOnly stores two equal-looking points twice and cannot find a new one, though their hashes match. Then show two more ways the same trap appears: a subclass of Both that overrides __eq__ and so loses its inherited hash, and a plain @dataclass against @dataclass(frozen=True). End with the working classes on the same input.
A Tag class compares its text without case (self.text.lower() == other.text.lower()) but hashes the raw text with poly_hash, so equal tags can have different hashes. STEP 1: put Tag("Apple"), Tag("apple") and Tag("APPLE") in one set and print its length and two lookups. STEP 2: build a minimal chaining set (a lookup scans one bucket with ==), add Tag("apple"), and look up all 32 capitalisations of "apple" with m = 8, 16, 32 and 64. Show that exactly the spellings in its bucket are found, and explain why small tables hide the bug. STEP 3: fuzz on 2,000 seeded pairs of a short word and a re-cased copy. A pair fails when equal tags miss each other in a set, or when the set's length is wrong. Catch exceptions and count them as failures, and report the smallest failing pair by (length, word, other). STEP 4: fix __hash__ so it hashes the same normalised form that __eq__ compares, and rerun the fuzz. Say why the contract a == b implies hash(a) == hash(b) is needed.
Numbers that compare equal are the same dict key. Show that {1: 'a', 1.0: 'b', True: 'c'} keeps one entry, and say which key and which value survive. Then show three float traps. First, 0.1 + 0.2 misses the key 0.3. Count how many of the 100 sums i/10 + j/10 (for i and j in 0..9) miss their key k/10. Second, two float("nan") keys are stored separately. Third, a NaN key is found only through the same object. Then fix all three. Use integer cents. Use Fraction keys (count the misses again). Use a stated tolerance: show that round(x / tol) splits two values 2e-9 apart, then build a NearMap that snaps to floor(x / tol) and checks the two neighbouring cells as well. Fuzz NearMap against a full scan on 2,000 seeded cases, and count exceptions as failures.
Count 5,000 seeded words (from 500 distinct) with defaultdict(int), then check 3,000 seeded queries with if counts[q]:, most of which are not in the text. Print len(counts) before and after, a query word the text never contains that is now in counts, and the number of zero entries the reads created. Show that a defaultdict(list) grows the same way when you only loop over a group. Then fix the check with in and with .get(q, 0), and show the hit counts agree and nothing is inserted. Finally show that Counter returns 0 for a missing key without inserting it, though c[x] += 0 still inserts. In a comment, say how this differs from the lingering zero counts in DSA Topic 5.
Remove the zero-stock items from a dict inside for k in d:. Catch the RuntimeError and print it, together with what was removed and what was left. Show that it is still raised when the deleted key is the last one, and that a set behaves the same way. Show that changing values in the loop is allowed. Then delete one key and insert another inside the loop, so the size does not change, and print which keys the loop visited and whether any error was raised. Fix the original task in three ways: loop over list(d), build a new dict with a comprehension, and collect the keys first and delete them after the loop. Give each fix's cost. End with the contrast: removing from a list inside its own loop raises nothing and silently skips items.
A linear-probing ProbingMap deletes with a DELETED tombstone, so probe chains stay intact, and put reuses the first tombstone on its path. Its load factor counts live keys only, so it resizes when n / m > 0.75. Give every scan a probe cap of m: a walk stops at an empty slot or after m probes, and a scan that hits the cap is counted. STEP 1: run a churn workload from random.Random(7) on a table of 64 slots that holds about 16 live keys. Each step inserts one new key and deletes one random live key. At steps 10 to 1,000, print the live keys, tombstones, empty slots, the average probes of 200 misses, how many of those misses hit the cap, and the rebuild count. Then run the fixed version, which rebuilds when (n + tombstones) / m > 0.75 (doubling m only if the live keys need it), on the same workload. Print the final miss cost of both, computed from the table. STEP 2: fuzz both versions against a dict, counting wrong answers and exceptions as failures. Explain what happens to a get written without the cap, and why the fix's rebuilds cost amortised O(1).
A chaining HashMap whose resize step was left out keeps m = 64 buckets forever. Insert n = 1,000, 4,000 and 16,000 seeded int keys into it and into the same table with resizing at 0.75. Time a get of every key with best_of, and print nanoseconds per get together with m and alpha for each. From the printed numbers, compute how much the time per get grew for each table while n grew 16x. Then show that open addressing without resizing cannot hold more than m keys. Put 9 keys that all start at slot 0 into an 8-slot probing table whose put stops after m probes and raises RuntimeError. After each put, print how far a miss probes. Say what the unguarded while loop would do.
Each of these hashes looks reasonable until it meets the wrong data. Sum of ords meets 5,040 anagrams of "abcdefg". x ^ y meets all (from, to) pairs in 0..69. x * y meets a 70 x 70 grid around the origin. Hashing the first 8 characters with poly_hash meets 5,000 seeded shop URLs. For each one, put the keys into m = 1,024 buckets and print the buckets used, the longest chain, and the comparisons needed to find every key once. Then do the same with the fix: poly_hash of the whole string, or hash() of the tuple. The poly_hash fix for the anagrams still leaves a long chain. Compute how far it is from n / m, and show what a prime m changes. Print one colliding example for each bad hash, and say what each one throws away.
STEP 1: use subprocess and sys.executable to run print(hash('apple')) in child processes with PYTHONHASHSEED set to 1, then 1 again, then 2. Print only whether the outputs match, and do the same for hash(12345). STEP 2: show why salting exists. "Aa" and "BB" have the same poly_hash, so 10 blocks give 1,024 strings that all collide. Put this family into 1,024 buckets with the public poly_hash, with a secret start value h0, and with a secret base (both drawn from random.Random(7)). Print the buckets used, the longest chain and the compares needed to insert the family. Explain why the secret start value does not help. STEP 3: show the cost. In child processes, compare the printed order of one set of strings under seeds 1, 1 again and 2, then do the same for sorted() of that set and for a dict's order.
Some code only works because of an order that nobody promised. Three habits, each shown beside its fix. (1) list(set(items)) has the order of the hash table, which depends on the order the items arrived in whenever two of them collide; the fix is sorted(set(items)). (2) Counter.most_common(1) breaks ties by first arrival, so the "most common word" changes when the same words arrive in another order; the fix is an explicit tie-break on (-count, word). (3) dict == dict ignores key order, but OrderedDict == OrderedDict does not, so two equal configurations compare unequal once they went through an OrderedDict; the fix is to compare what you mean, dict for "same contents" and list(d.items()) for "same contents in the same order". Run each habit and its fix on the same data in 200 seeded shuffles and print how many different answers each produced: a function whose answer depends on arrival order gives more than one, and a fixed one gives exactly one. Any exception in a shuffle counts as a failure. A set of strings also changes order from one run to the next (the string hash is salted, see the earlier topic on hashing), but printing it would make this output differ per run, so the demonstration uses integers, whose hashes are fixed.
A dict groups things by key, so a key that is wrong for the problem merges things that differ or splits things that are the same, and no hash quality can repair that. Four wrong keys, each next to a right one. (1) frozenset(word) as the key for "same letters", which puts "aab" with "ab" because a set forgets how many times a letter occurs; the right key is tuple(sorted(word)). (2) "".join(parts) as the key for a list of parts, which makes ["ab", "c"] equal ["a", "bc"]; the right key is tuple(parts); also show that joining with "|" is only safe until a part contains a "|". (3) str(point) as the key for a point, which treats [1, 2], (1, 2) and the text "[1,2]" as three points because the spelling differs; the right key is a tuple of ints parsed from each. (4) id(obj) as the key for an object, which is reused after the object is freed. For (1) to (3) write audit(items, keyfn, same): over all pairs, count false merges (equal keys, different by the truth function) and false splits (different keys, equal by the truth), and print the wrong key beside the right one. For (4) print how many distinct id values five short-lived objects produce, against five kept alive.
A dict lookup is O(1) once you hold the key. Building the key is part of the lookup, and it can cost far more than the lookup itself. Measure three things. (1) Key construction against lookup: for words of 4,000 and 40,000 letters, time key_sorted(w) ("".join(sorted(w)), O(k log k)), key_counts(w) (one pass of counter increments, then a 26-item tuple, O(k + 26)) and one dict lookup with a key that is already built, each on its own, and print how many times a lookup the build costs plus how each time grew when the word became 10 times longer. (2) Hash caching: CPython stores the hash inside a str, so a second lookup with the same string reuses it. A tuple is version-dependent (CPython up to 3.13 recomputes a tuple's hash on every lookup; 3.14 caches it), so the demonstration uses a RehashKey class whose __hash__ loops over its items on every call, which rehashes on any version. Time lookups of the same key object for a str and a RehashKey of 2,000 and of 20,000 items, and print nanoseconds per lookup and the growth. (3) The fix: a small CachedKey that runs the same loop once and returns the stored result from __hash__; show that its lookup stays flat, that two equal CachedKey objects still find each other, and that the rule is build the key once and keep it.
sys.getsizeof(a_set) reports the table and nothing it points at. For a set of 20,000 strings, 64 characters each (hex text from seeded random bits), measure with tracemalloc what the set really holds on to: the traced bytes after building it, against getsizeof, and print how much of the total is hidden. Then replace each string by a 64-bit fingerprint (mix(poly_hash(s)), using the topic's polynomial hash and a 64-bit finaliser, so the numbers are the same on every run) and measure the set of fingerprints the same way. Say how much memory the swap saved, and show from the printed numbers that the table part is the same size either way. The price is a false-positive risk: for fingerprints truncated to b bits, compute the birthday-bound chance of any collision among the 20,000, 1 - exp(-n * (n - 1) / 2^(b + 1)), and count the colliding pairs actually found at 24, 32, 40 and 64 bits next to the expected count n * (n - 1) / 2^(b + 1). Finally probe 20,000 strings that were never inserted against the 24-bit set and count false "found" answers against the expected 20000 * n / 2^24 (n = 20,000).
Nine hashing bugs have come up in this set: a mutable key, a broken hash/eq contract, float keys, a defaultdict that grows on reads, tombstones that were never left behind, a table that never resizes, a bad hash, reliance on order, and colliding keys (a key that merges things that differ). Build one harness that catches every one by name. Each case has a buggy implementation, a fixed one and a check that returns None when the implementation is fine and a short description of the failure otherwise. The checks are small differential tests against a trusted reference (a plain dict, a brute-force pair comparison, or a stated invariant). Run every check on both implementations, catch exceptions inside the harness and count them as failures, and print a catch table. Then assert two things: all nine buggy versions are caught, and none of the nine fixed versions raises a false alarm. Label the parts with # STEP comments: (1) the engines and the nine implementation pairs, (2) the nine checks, (3) the harness and its table.
Build a complete separate-chaining HashMap that behaves like a dict. Buckets are lists of [key, value] pairs, m starts at 8, and the table doubles when n / m passes 0.75. It supports m[k] = v, m[k], del m[k], k in m, len(m), m.get(k, default), iteration over keys and items(). It validates: an unhashable key raises TypeError, a missing key raises KeyError on m[k] and del m[k], a non-callable hash_fn raises TypeError, and growing the table while iterating raises RuntimeError. Mirror dict for equal keys (1, 1.0 and True are one key) and for a key that is its own nan.
The steps are: STEP 1: demo, including the errors. # STEP 2: fuzz against a real dict on 20,000 seeded operations over a mixed key pool (ints, floats, bools, strings, tuples, and unhashable lists), comparing every return value and every exception class, and the full contents every 500 operations; exceptions raised by the harness itself count as failures. # STEP 3: time 50,000 puts and 50,000 gets against dict, each piece on its own. # STEP 4: three things dict does differently, measured: it keeps insertion order, it mixes the hash so patterned keys do not pile up (keys i * 1024 all share bucket 0 while m <= 1024), and it runs in C.
Build a Cache(capacity, policy) service on collections.OrderedDict, with get(key, default=None), put(key, value), keys() (least to most recently used) and counters for hits, misses and evictions. policy is "lru" (a hit moves the key to the end) or "fifo" (a hit moves nothing, and an overwrite keeps the key's place). The policy must apply on every path: get and put of an existing key. It validates: capacity must be an int (not a bool, TypeError otherwise) and at least 1 (ValueError), policy must be one of the two names (ValueError), and an unhashable key raises TypeError without changing any counter. Do not import functools (its lru_cache is memoisation, DSA Topic 8).
The steps are: STEP 1: demo. # STEP 2: fuzz against a list-based CacheTruth that applies the policy on both paths, on 500 seeded sequences for both policies, comparing results, key order and counters after every step, plus the constructor validation by exception class; exceptions in the harness count as failures. # STEP 3: back the O(1) claim by timing the Cache service itself: 40,000 fresh puts (each one evicts) at capacity 100 and at 10,000, and print the growth. A plain dict used the same way (del d[next(iter(d))]) is only a comment: it was measured earlier in this topic and is not O(1) in CPython. # STEP 4: a seeded Zipf-skewed trace of 20,000 requests over 1,000 keys, LRU against FIFO hit rates at five capacities, with the first 5,000 requests also replayed through CacheTruth.
Build a one-edit spell checker. From a seeded corpus (40,000 tokens drawn with Zipf weights from a vocabulary of made-up words), keep a Counter of word counts: its keys are the word set. edits1(word) generates every string one edit away, by delete, swap of adjacent letters, replace and insert over a to z. suggest(word) returns the word itself if it is known; otherwise it keeps the candidates that are in the word set and picks the best by (-count, word); with no candidate it returns the word unchanged. suggest validates: non-strings raise TypeError, and empty or non-lowercase-letter strings raise ValueError.
The steps are: STEP 1: for word lengths 3 to 10, print the number of candidates generated (the probes) against the formula 54 * n + 25, and how many are distinct. # STEP 2: fuzz against suggest_truth, which scans the whole vocabulary with a direct "is this one edit away" test and shares no code with edits1, on 400 seeded corruptions (one edit of each kind, two edits, none) and on the invalid inputs, comparing results and exception classes, with exceptions in the harness counted as failures. # STEP 3: time 100 suggestions against the vocabulary scan, each on its own.
Build find_duplicates(root, digest) that finds files with identical content. Hashing every file reads every byte, so go in stages: (1) group by size, which needs no read; a file whose size is unique cannot have a duplicate. (2) For each size group of two or more, group by digest(path), hashlib.sha256 of the content by default. (3) Confirm byte equality inside each digest group, because a digest only suggests equality (the engine must apply the digest it is given on every path, so it works with a weak digest too). It validates: root must be a str or path-like (TypeError), must exist (FileNotFoundError), and must be a directory (NotADirectoryError); digest must be callable (TypeError). Return the groups as sorted lists of /-separated relative paths, plus stats: files seen, files hashed, files whose full read the size step avoided, and the bytes avoided.
Work in a tempfile.mkdtemp() sandbox and delete it at the end. # STEP 1: a seeded tree of 21 files with three copies of one 5,000-byte blob, a look-alike of the same size and same byte sum that differs, two copies of a 20,000-byte blob, two empty files, and twelve unique files. # STEP 2: fuzz 40 seeded random trees against dups_truth, which reads every file whole and groups by the content itself, with sha256 and with a weak digest (sum of bytes mod 251), comparing groups and exception classes, and counting how often the confirm step had to split a digest group; exceptions in the harness count as failures.
Build an InvertedIndex over documents (strings). Each document is lowercased and split on whitespace; the index maps every word to the set of document ids that contain it. query(all_of=(), any_of=(), none_of=()) returns a sorted list of ids: documents containing every all_of word (AND), at least one any_of word (OR, if that list is non-empty) and none of the none_of words (NOT). With no positive terms the NOT applies to all documents. Unknown words are legal and match nothing. Start the AND from the smallest posting set. It validates: each argument must be a list or tuple (TypeError, so a bare string "cat" is rejected instead of being read as letters), each term must be a str (TypeError) and neither empty nor containing whitespace (ValueError).
The steps are: STEP 1: build it over 3,000 seeded documents of 30 words from a 400-word vocabulary (about 10% capitalised) and run a sample query. # STEP 2: fuzz 600 seeded queries, including invalid ones, against query_truth, which scans every document's token list and has its own validation, comparing results and exception classes; harness exceptions count as failures. # STEP 3: time 60 queries by index against the scan and the index build, each piece on its own, print totals at 1 query and at 1,000 queries by addition, and the break-even query count found by search.
A payment service receives events like {"user": "U17", "action": "pay", "request_id": 1042, "attempt": 1, "ts": 10420}. Clients retry, so the same request arrives again later with a higher attempt, a later ts, and sometimes the user name re-serialised as " u17". Build a deduplicator that lets each request through once. Generate a seeded stream of 6,000 requests with retries (random.Random(7)), and write it in three steps. (1) The key decides what a duplicate is. Write canonical_key (the normalised user, the action and the request id) and dedupe with an unbounded set. Beside it, run two keys a student might write: the whole event as a sorted tuple of items, and the right three fields without normalising the name. Print how many duplicates each lets through. (2) Bounded memory. A service cannot remember every key forever. Write BoundedDeduper(limit), which keeps only the last limit distinct keys and evicts the oldest by insertion order, with every operation O(1). Fuzz it against a slow list-based reference on 300 seeded streams. (3) Missed duplicates against N. Print a table of missed duplicates for several window sizes. Compute from the stream the smallest N that misses nothing (1 + the most other new keys that arrive before a retry, because the request's own key also takes a slot), and check that N misses none and N - 1 misses at least one. Compare the window's memory with the unbounded set's.
Build a collision lab that compares three collision strategies under a good hash and a bad one, at load factors 0.25, 0.5, 0.75 and 0.9, in one table of 1,024 slots. The strategies are separate chaining, linear probing, and CPython-style perturbed probing: start at j = h % m with perturb = h, and on each collision do perturb >>= 5, then j = (5 * j + 1 + perturb) % m. The keys have structure, as real ids often do: they are seeded random multiples of 64. The bad hash is the identity (what hash(n) is for small ints). The good hash is splitmix64's finaliser, which mixes every input bit into the low bits. For each strategy, hash and load, record the average and the longest number of probes a successful lookup needs, and print them as one table. Then explain the bad hash from the keys (how many home slots do they have?). Finally, draw the conclusion from the table's own numbers: the slowdown each strategy suffers from the identity hash at each load, which strategy is least hurt, and which has the longest single probe sequence at 0.9. Say why perturbed probing survives patterned keys, and what would defeat all three.
Conway's Game of Life on an unbounded board: store only the live cells, as a set of (r, c) tuples. One step counts, for every cell next to a live cell, how many live neighbours it has, using a Counter. A cell is alive next step if it has 3 live neighbours, or 2 and it is alive now. Run a glider for 40 steps, print it in ASCII at step 0 and step 40 with its bounding box, and check that it has the same shape, moved by (10, 10). Then show two wrong boards. The first is a student's step that loops over the live cells only, so it never sees the dead cells where births happen. The second is a fixed 8x8 grid that treats cells outside it as dead. Print what each turns the glider into. Fuzz the set version against a padded fixed grid on 60 seeded random soups, padding each by the number of steps plus 2 so that the wall cannot interfere. Finally, compare the memory of the 5-cell set with that of a grid big enough for the glider's trip of 1,000 cells. State the cost per step of both representations.
Build a URL shortener with two dicts, code -> url to expand a link and url -> code so that shortening the same URL twice returns the same code. Compare two ways to make codes, on 20,000 distinct seeded URLs. (1) A base-62 counter: the n-th URL gets base62(n). Codes never collide, but they are sequential and so guessable. Print the length of the last code. (2) A truncated hash: mix(poly_hash(url)) % 62^L, written in base 62 and padded to L characters, where mix is splitmix64's finaliser, so that similar URLs get unrelated codes. Count the colliding pairs for L = 6, 5, 4 and 3 against the birthday estimate n(n - 1) / (2 * 62^L), and compare the measured growth from 4 characters to 3 with the estimate's. (3) What a collision does. Run a shortener that overwrites the code -> url entry when a code is taken, and one that retries with a salt (url + "#" * attempt) until the code is free. Print how many issued links now open the wrong page under each. Never print hash() of a string.
Settle "which membership structure should I use?" with one benchmark. Compare a list scan (x in list), a sorted list + bisect, the hand-built chaining table and a set, for n = 100, 10,000 and 100,000 seeded distinct ints, with about half the queries hits. First check that all four give the same answer for every query. Then time each structure's build and its per-lookup cost separately with best_of. The list needs no build, because the data already arrives as a list. Never get one cost by subtracting two timings. Print both as one table. From those same numbers: (1) divide each method's per-lookup cost at the largest n by its cost at the smallest, and print it beside what the complexity predicts (n for the scan, log n for bisect, flat for the two hash tables), with bisect's exact number of halving steps at each n. Say what else besides the work makes every measured cost rise. (2) Print the constant factor of the hand-built table against the set, for build and for lookup at each n, and sorted build against set build. End with a conclusion that follows from those printed rows, including when sorted + bisect is still the right choice.
The interviewer says: "Explain how a hash table works. Assume I know nothing." Write your explanation as a program, where every claim comes with a few printed lines that back it up. Cover six points in order. (1) A hash function turns a key into the same number every time. Use your own poly_hash, never hash() on a string, and show that "cat" and "act" differ. (2) Buckets: the number mod m picks one list. Print the buckets for int keys 3, 11, 19, 4 and 7 with m = 8. (3) Collisions are certain: 9 keys into 8 buckets must share one. Show which words share a bucket. (4) Load factor and resizing: insert 100 keys, print the bucket counts the table went through and the total number of keys the resizes moved, and check it against 2n. (5) Average against worst: average probes for a hit with seeded random int keys, against a key class whose hash is a constant, for n = 1,000. (6) Hashability: why a list cannot be a key and a tuple can, and the hash/eq contract. End with the follow-ups an interviewer is likely to ask (ordered keys, top-k, prefix lookups, "is Python's dict like this?"). Answer each in one line that names the right tool and the topic that teaches it, without building it.
An interviewer hands you five hashing functions. Each one has one bug. The rule of the exercise: read the code, name the bug, and write down the failing input and the wrong output you expect before running anything. Then run it to confirm. The five:
- Group words by first letter, starting from
dict.fromkeys(letters, []). - Two-sum that checks
if seen.get(target - x):before returning a pair. - Two-sum that inserts
xinto the map before it looks uptarget - x. - A word counter in a
defaultdict(int)that testsif counts[q]for each query and then reportslen(counts)as the number of distinct words. - A filter that drops a stop word, with the stop set built as
set(stop_word).
For each one, print the reasoning, the prediction, the actual output and the truth, whether the prediction held, and what the fixed version returns. Then fuzz every bug and every fix on 1,000 seeded inputs, counting exceptions as failures. Two-sum accepts any valid pair, so check a property rather than one pair: None exactly when no pair exists, otherwise i < j and the sum matches. Each bug must fail at least once and each fix never. State the complexity of the correct versions.
The interviewer: "We store 50,000 records by integer key. Today the traffic is exact lookups. Next quarter, product wants range counts ('how many keys between lo and hi') and nearest key queries. Design it." Compare three designs: a dict, a sorted list + bisect (with values in a parallel list), and both kept in sync (a dict for exact lookups, a sorted key list for order, with every insert updating both). First, fuzz all three against a brute force on 300 seeded sequences of insert, get, range and nearest operations, where a nearest-key tie goes to the smaller key. Then measure the cost of each primitive once at n = 50,000: dict get, dict put, dict range scan, dict nearest scan, bisect get, insort, bisect range and bisect nearest. Price three workloads from those same numbers: a lookup service (200,000 gets), a dashboard (200,000 gets, 2,000 ranges, 500 nearest) and an ingest-heavy job (50,000 inserts, 50,000 gets, 5 ranges). Choose a design for each, and break equal costs by preferring fewer structures. Say what you would use if inserts and range queries were both heavy, naming the topic that teaches it.
A mock interview, written as a transcript that runs. The opening problem is two-sum: given nums and target, return indices i < j with nums[i] + nums[j] == target, or None. Clarify first, then give the brute force and the one-pass map. Because any valid pair is accepted, the fuzz compares a property, not the exact pair. The interviewer then fires three quick follow-ups you have met before: count the pairs, the input is sorted, and a stream of add/find. Answer each in one printed line that names the tool and the topic that teaches it. Then answer four new follow-ups, each checked against a brute force on seeded inputs (random.Random(7)), with exceptions counted as failures:
- The two indices must be at least k apart (
j - i >= k). Keep the map one pass, using a delayed insert. - The values are floats and "sums to target" means within
eps. Show the exact map missing[0.1, 0.2]with target 0.3, then bucket the values byfloor(x / eps)and check the complement's bucket and its two neighbours. - An attacker chooses the numbers. In CPython an int's hash is the int mod
sys.hash_info.modulus, and ints are not salted. Build 3,000 values that all hash to 0, time the map on them against random ints, and time a sort-and-walk answer that does not hash at all. Say which guarantee each one gives. - The data is too big for memory. Partition the values into 16 chunks (lists standing in for files) so that each chunk can be solved alone. Show that partitioning by
xloses pairs, and that partitioning bymin(x, target - x)keeps every pair in one chunk. Print both counts beside the truth on 40,000 values, with the largest chunk's size.
Close by naming the tools for further follow-ups (pairs in order, the k smallest sums, three-sum), without building them.
The capstone: build a small key-value store from the parts of this topic. It has three layers, and every path that adds or drops a record must update all three.
- Storage: a hand-built open-addressing table with linear probing and
DELETEDtombstones. It rebuilds when live keys plus tombstones pass 0.75 of the slots, doubling only when the live keys need it, so churn cannot fill the table with tombstones. It takes a hash function. Use a salted string hash:poly_hashwith a secret base and start value drawn from a seededrandom.Random, then splitmix64's finaliser. Say in a comment where a real store would get its salt. - Eviction: an LRU layer with a capacity, using an
OrderedDictfor recency (move_to_end,popitem(last=False)). Reads and writes count as uses; index queries do not. - A secondary index: field -> value -> set of keys, so that
query(all_of, any_of, none_of)answers AND, OR and NOT by set algebra. Results are sorted, because set order is not promised.
Run six workloads, each printing a few lines: (1) put, update, get and delete, showing that an update re-indexes the record; (2) 20,000 inserts and deletes over 50 live keys, printing the slot count, the rebuilds, the tombstone share and the probes per miss against Knuth's estimate; (3) a skewed seeded LRU trace of 20,000 gets, checked call by call against a model; (4) three index queries on 500 records, checked against a full scan; (5) the colliding family of 1,024 strings built from "Aa" and "BB" blocks, under the unsalted and the salted hash: distinct hashes, probes per insert and fill time; (6) a fuzz of the table against dict and of the whole store against a model that applies the same LRU policy and brute-force queries, with exceptions counted as failures. Include a store whose eviction path forgets the index, show that the fuzz catches it, and print one wrong query it returns. State the complexity of every operation.
Stuck? Solve it with a mentor.
Your first 1-on-1 session is free.