Library

Coding patterns that get asked

The data structures and patterns behind the coding questions candidates report most, each one built up in code you write, then used on a question from a real loop.

Practice questions

114
Hash maps and sets: group, count, look up
  1. 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. 2.Which of these can be a key in a Python dict?
  3. 3.What does {1: "int", 1.0: "float", True: "bool"} evaluate to?
  4. 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. 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. 6.In the two-sum loop, you write seen[size] = j before checking need in seen. What happens with sizes [750, 100] and capacity 1500?
Two pointers and the sliding window
  1. 1.A loop moves right over n entries, and an inner while loop moves left forward to shrink the window. In total, across the whole pass, how many times can the inner loop run?
  2. 2.sizes is sorted. With lo at the first index and hi at the last, sizes[lo] + sizes[hi] is bigger than the target. Which move is safe?
  3. 3.You keep a window of the last 2 log entries in a set, adding the key that enters and removing the key that leaves. The log is ana, ana, bo. What does the set hold for the window [ana, bo]?
  4. 4.A limiter allows 2 requests per 10 seconds per client, with a sliding window. A client's requests at 8 and 9 were allowed. What happens to its request at 10?
  5. 5.You want the longest stretch whose total is at most a budget, and the numbers can be negative. Why does grow-right, shrink-left stop working?
  6. 6.A limiter keeps a dict from each client to a deque of its request times, cleaning a deque when that client sends again. After a day it has seen 10 million clients, most of whom sent one request. What's wrong, and what fixes it?
Sorting, then binary search on the answer
  1. 1.times = [100, 130, 130, 130, 220]. What do bisect_left(times, 130) and bisect_right(times, 130) return?
  2. 2.A binary search uses lo, hi = 0, len(a) and while lo < hi, with mid = (lo + hi) // 2. Someone writes lo = mid in the branch where a[mid] is below the target. What happens?
  3. 3.A store keeps each key's change times sorted in times and the values in values. A read does values[bisect_right(times, t) - 1]. What does it return for a t before the key's first change?
  4. 4.A log of (key, time, value) arrives out of order, and two changes can share a time, in which case the later one wins. Values can be dicts. How should you sort it before building each key's history?
  5. 5.Which of these questions can you answer with a binary search on the answer?
  6. 6.A store with 10,000 keys takes a snapshot after every 100 changes. One design copies every key's current value at each snapshot. The other keeps, per key, a list of (snapshots taken so far, value) after each change, and a snapshot only adds 1 to a counter. What does a snapshot cost in each?
Heaps: always know the smallest
  1. 1.A heap holds n items. What does it cost to look at the smallest, to pop it, and to push a new item?
  2. 2.After heapq.heapify(h), h is [7, 12, 18, 30, 21, 45, 60]. Which gives the four smallest items?
  3. 3.You push (expires, credit) onto a heap, where each credit is a dict, and two credits expire at 30. What happens?
  4. 4.To keep the 3 closest points, you push (dist, point) onto a heap and pop whenever it holds 4. Which 3 points does it keep?
  5. 5.Each meeting holds a room for start <= t < end. Before placing a meeting that starts at start, which line frees the rooms that are done?
  6. 6.Your heap of [expires, count, credit_id, left] entries holds a credit that was cancelled. What should you do?
Stacks, and the monotonic stack
  1. 1.You push 1, 2 and 3 onto a stack, then pop twice. What comes out, and what does each operation cost on a Python list used with append and pop()?
  2. 2.One sample shows ["main", "load", "parse"] at time 30 and the next shows ["main", "save"] at time 40. What events come at time 40, in order?
  3. 3.Two samples in a row show ["main", "a", "b"] and then ["main", "b"]. What happened between them?
  4. 4.f calls itself: the outer call runs from 0 to 40 and the inner one from 10 to 30, and nothing else runs inside them. What is f's total time, callees included?
  5. 5.The monotonic stack's next-larger loop has a while inside a for. Why is it O(n) and not O(n²)?
  6. 6.A loop calls a 2 ms function a thousand times, and a sampler takes a sample every 10 ms. Which result can you trust?
Intervals: merge, cover and schedule
  1. 1.Two half-open intervals are (s1, e1) and (s2, e2), start in and end out, each with its start before its end. Which test is true exactly when they overlap?
  2. 2.Free time walks busy blocks in start order, (12, 15), (13, 14), (15, 16), in a day from 12 to 17, but sets free_from = end instead of max(free_from, end). What does it report?
  3. 3.Half-open reservations (1, 4), (4, 7) and (7, 9) go through a sweep that sorts its events so that, at one time, starts come before ends. How many machines does it say are needed?
  4. 4.A rotation runs from day 1 through day 7, closed. Engineer A is free days 1 through 4, and engineer B days 5 through 7. Can A hand off to B?
  5. 5.You want the set of machines with enough GPUs that costs the least, then has the fewest machines. You try sets smallest first with combinations. Can you stop after the first size that has a set that fits?
  6. 6.Shifts are closed day ranges, and you need the fewest that cover days 1 through 14. Which choice, repeated, always gives the fewest?
Linked lists and the doubly linked list
  1. 1.Why is adding a node at the front of a linked list O(1), while xs.insert(0, x) on a Python list is O(n)?
  2. 2.To put a new node after node, which lines keep the rest of the list?
  3. 3.Nodes 0 to 7 form a list where node 7 points back at node 3. Floyd's slow and fast pointers meet at node 5. How do you find node 3?
  4. 4.List a is 2, 9, 7, 3, 6 and list b is 5, 1, 9, 7, 3, 6, where 7, 3, 6 are the same nodes in both. You level the lengths and then step both until the values are equal. What do you get?
  5. 5.Why can a doubly linked list unlink a node in O(1) given only that node, while a singly linked list can't?
  6. 6.You reverse a 5,000-node list with the short recursive version, one call per node, using Python's default settings. What happens?
Breadth-first search on a grid
  1. 1.You run BFS from one cell of a grid where every move is one step. The first time the search reaches a cell, what do you know?
  2. 2.You mark cells as seen when you pop them, not when you queue them, and you don't skip repeats. On an open 10 by 10 grid searched from a corner, how many entries come off the queue?
  3. 3.Fifty fires on an open 200 by 200 grid. You want the minute each tree catches. What does one search from every fire at once cost, against one search per fire?
  4. 4.A one-row forest F...., a fire on the left and four trees, one burning neighbor is enough. You update the grid in place, scanning left to right. What does your code report?
  5. 5.Your level-by-level loop adds a minute after every pass, including the pass that finds nothing new. What does it return for a row of five trees lit at one end?
  6. 6.In the forest F.F / ... / F.., a tree needs two burning neighbors to catch. The bottom-right tree is two steps from the nearest fire. When does it catch?
Depth-first search and recursion on trees
  1. 1.Why does a walk down a tree from its top not need a seen-set, when a walk over a grid does?
  2. 2.A recursive size written as 1 + sum(size(child) for child in children[node]) handles a chain of 499 nodes and raises RecursionError at 500. Written with a plain for loop, it reaches 999. Why the difference?
  3. 3.Which of these can only be computed after a node's children are done?
  4. 4.With your own stack, you record the order regions come off it, then compute subtree sizes walking that order. Which direction works?
  5. 5.Word search marks each cell it steps on. What breaks if it never unmarks a cell when it backs out?
  6. 6.You keep a total per node and walk up the parents on every change. On a chain of 100,000 nodes, what does a change at the bottom and a read of the top cost?
Topological sort: tasks with prerequisites
  1. 1.In Kahn's algorithm, when does a task go on the queue?
  2. 2.Kahn's algorithm stops with 3 of 7 tasks in the order. What do you know about the other 4?
  3. 3.A pipeline has V tasks and E pairs. What does Kahn's algorithm cost, and what does rescanning the list for a ready task cost at worst?
  4. 4.Your depth-first sort keeps one seen-set and raises a cycle error whenever it reaches a task already in it. What happens on a pipeline where deploy needs both test and package, and both need compile?
  5. 5.package takes 2 minutes and needs compile, which finishes at minute 7, and assets, which finishes at minute 5. Kahn's pops compile first, then assets. With as many workers as you like, when does package finish?
  6. 6.You run the lesson's dfs_order, which follows unblocks, on a chain of 5,000 tasks, each needing the one before and listed first task first, with Python's default settings. What happens?
Tries: prefixes and autocomplete
  1. 1.A trie holds tent and tents, and nobody inserted ten. What tells you ten isn't a word?
  2. 2.What does checking whether some word starts with a prefix of p letters cost in a trie of n words?
  3. 3.You count, on every node, the words that pass through it. Which word has no prefix that only it starts with, among tent, tents and tarp?
  4. 4.Autocomplete keeps the best k words on every node. What gets expensive?
  5. 5.Every suffix of yoyo, kayak and pole goes in one trie, and each node counts every visit. What does yoyo get as its shortest unique fragment, and why?
  6. 6.You have a fixed list of 100,000 words and must count the words under a prefix, with memory tight. What would you use?
Dynamic programming on a table
  1. 1.What makes an order of filling a dynamic programming table correct?
  2. 2.For the longest increasing run with one deletion, why does the table need a row for nothing deleted and a row for at most one deleted?
  3. 3.In the edit distance table, what does moving from d[i - 1][j] to d[i][j] stand for?
  4. 4.Several routes share the best score, and you must return the one whose list of junctions comes first. A forward pass that keeps a parent for each junction returns a best route that isn't that one. What fixes it?
  5. 5.A lift is added that carries riders from an exit back up to the trailhead, and every lap of the loop is worth points. What happens to the best route?
  6. 6.A route may ride at most k expert stretches. Why does the table need a cell for every junction and every count up to k?
Count a tree you can only message
  1. 1.Machine 1 has children [3, 4]. Its handler finishes when the last child in the list, 4, has answered. When does this go wrong?
  2. 2.The network delivers some messages twice. Which way of keeping a machine's answers stays right?
  3. 3.The answer from machine 1 to the root was lost, after 1 had finished. The root's tick asks 1 again. What should 1 do?
  4. 4.Only the root has a timer. The ask from machine 1 to its child 3 is lost. What happens?
  5. 5.Two counts, a and b, run at once. Machine 1 keeps one parent, one dict of answers and one kept answer. What goes wrong?
  6. 6.A tree of 1,000 machines is a single chain. With nothing lost, how many messages does a count send, and how many rounds does it take if each message takes one round?
Caches: LRU order and time limits
  1. 1.An LRU cache must answer get and put in O(1). Why does the classic design pair a hash map with a doubly linked list?
  2. 2.An OrderedDict used as an LRU cache holds a, b, c, oldest first. You run d["a"] = 10. What's the order now?
  3. 3.An entry is written at time 100 with ttl=30, and the cache uses the rule live while now < expires_at. At which time does get first return the default?
  4. 4.Key a is written at t=0 with ttl=5, then written again at t=1 with ttl=100. At t=5, purge pops the heap entry (5, 0, "a"). What should it do?
  5. 5.A cache with capacity 2 holds a (live, least recently used) and b (expired at t=3). At t=10 you put a new key c. What happens?
  6. 6.Four threads share the linked-list LRU cache. Which statement matches what the measurement showed?
Design a memory allocator: free lists and intervals
  1. 1.An arena of 7 units has free runs (0, 3) and (4, 7), half-open, with a live block at unit 3. What does first fit return for a request of 4 units?
  2. 2.The free list is [(0, 4), (8, 12)] and the block (4, 8) is freed. What should the free list be afterwards?
  3. 3.An arena of S units holds k free runs. What does first fit cost per allocation with one slot per unit, and with a free list?
  4. 4.Why does a C allocator never move a live block to merge the free space into one run?
  5. 5.The free list is [(3, 64)]. A request asks for 16 units aligned to 16. What does alloc return, and what is the free list afterwards?
  6. 6.release(owner) runs for start in self.owned[owner]: self.free(start), and free removes each start from self.owned[owner]. What happens when the owner holds two blocks?
A pipeline of transforms, then make it parallel
  1. 1.On standard CPython, a pure-Python function that only computes runs on 8 items. You switch from a plain loop to ThreadPoolExecutor(max_workers=4). What happens to the wall time?
  2. 2.You collect a thread pool's results with [f.result() for f in as_completed(futures)]. The first table is the slowest. What do you get?
  3. 3.Which step list can a ProcessPoolExecutor send to a worker?
  4. 4.A batch of 1,000 tables runs a step list whose third step is a typo, ("srot", 0). What should the batch do?
  5. 5.One huge table is cut into bands of rows that run in parallel. Which step can run on each band separately and still give the same answer as on the whole table?
  6. 6.You call pool.map(work, records()), where records() is a generator of 200 records, on 4 threads. How many records has the generator produced when the first result comes back?
A work queue that survives failures
  1. 1.w1 reserves task a. Then w2 calls ack("w2", "a"). What should the queue do?
  2. 2.a, b and c are enqueued in that order. w1 takes a, w2 takes b, and w1 fails a. What does the next reserve return?
  3. 3.max_attempts is 3. How many times can a task be reserved before it goes to the dead-letter queue?
  4. 4.A lease made at time 0 with a visibility timeout of 10. At what time does the holder's ack first return False?
  5. 5.A task with cooldown 4 has a lease that ends at 10. The queue first notices at 12. When can the task be reserved again?
  6. 6.A worker's lease ran out while its machine was frozen. It wakes up and writes its result after the next holder already wrote. What stops the stale write?
Rotate titles by score, with no repeats
  1. 1.The catalog is {Maple: 7, Harbor: 7, Comet: 9}. What does sorted(catalog, key=lambda t: (catalog[t], t), reverse=True) return?
  2. 2.Comet and Harbor have shown. Tundra rises from 3 to 10, and the billboard sorts its list again and keeps its cursor at 2. What goes wrong?
  3. 3.Comet has already shown in this loop. Its score drops from 9 to 1. Where does its new key go?
  4. 4.Why does a lazy-delete heap need the dict of current scores?
  5. 5.Three titles A, B and C showed in calls 1, 2 and 3, and the cooldown is 3. At call 4 every title is cooling. Which title shows?
  6. 6.Your billboard keeps scores in a Redis sorted set and reads them with ZRANGE ... REV. Maple and Harbor tie. Which comes first, and what's the fix?
No repeated titles on the first screen
  1. 1.Width 2. Row 0 is A, B, C and row 1 is C, D. What does row 1 become under level 1?
  2. 2.Your level 1 makes shown = set() inside the loop over rows. Which test catches it?
  3. 3.Under the screen rule, why is one forward index enough to fill a row?
  4. 4.Screen holds A and B, width 2, row B, A, C. Why does the row end after C instead of going on to B and A?
  5. 5.Under the grid rule, column 1 holds B, and the row is A, B with width 2. What does greedy by rank show, and what is the most it could fill?
  6. 6.You swap level 1's set for a Counter so each title can appear up to m times. Which test can still pass while the code is wrong?