Top 100 Software Development Engineer (SDE) Interview Questions and Answers
The questions most likely to come up in your Software Development Engineer (SDE) interview, ranked by likelihood, with senior-level answers that cover what the interviewer is listening for.
Curated: · Written: · Reviewed:
Q&A-1Two Sum: given an unsorted integer array with duplicates and a target, when would you use a hash map and when sorted two pointers? Compare time and space, and say how duplicates are handled.
The 90-second answer
For an unsorted array I use a hash map. One pass, O(n) time, O(n) extra space. Sorting first costs O(n log n) time, and I still need the original indices, so the two-pointer version ends up carrying O(n) extra space anyway. Two pointers wins only when the input is already sorted or when I must return values rather than indices and can afford an in-place sort without extra space.
Duplicates are handled by checking the complement before inserting the current element. That keeps the two indices distinct, so [3, 3] with target 6 returns [0, 1] and never pairs an element with itself.
def two_sum(nums, target):
seen = {} # value -> first index
for i, x in enumerate(nums):
j = seen.get(target - x)
if j is not None:
return [j, i]
seen.setdefault(x, i)
return []Trace on nums = [2, 7, 11, 15], target 9: i=0, x=2, complement 7 not seen, store 2 -> 0. i=1, x=7, complement 2 found at index 0, return [0, 1].
The setdefault matters. Overwriting with seen[x] = i would keep the last index, which is harmless for returning any valid pair, but storing the first keeps the lookup consistent when the same value appears several times.
| Approach | Time | Extra space | Keeps original indices | Duplicates |
|---|---|---|---|---|
| Hash map, one pass | O(n) average | O(n) | yes | check before insert |
| Sort plus two pointers | O(n log n) | O(n) with (value, index) pairs, O(1) values only | only with pairs | skip equal neighbours to dedupe output |
Two-pointer version, when the input is sorted or I only need values:
def two_sum_sorted(a, target):
lo, hi = 0, len(a) - 1
while lo < hi:
s = a[lo] + a[hi]
if s == target:
return [a[lo], a[hi]]
if s < target:
lo += 1
else:
hi -= 1
return []The failure to watch for is returning a pair of indices after sorting values in place, which silently returns wrong positions. Also, if the task asks for all unique pairs rather than one, the hash map needs a set of seen pairs or sorted output with explicit skipping of repeated values, and the time bound stays O(n) or O(n log n) depending on which path I took.
When I would not use a hash map: memory is tight and n is huge, the values are already sorted, or the input is streamed and cannot be stored. In those cases the sorted two-pointer scan over a bounded window is the defensible choice, and I say so explicitly.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-2When the sliding window for the longest substring without repeating characters meets a character it has already seen inside the window, where does the left index move?
The 90-second answer
The left index jumps to one position past the earlier occurrence of the repeated character. It does not step forward one slot at a time. If the window is [left, i] and s[i] already appears at index j with left <= j <= i, set left = j + 1. The window then holds no duplicate, and i - left + 1 is its length. The right index i always advances by one, so the whole scan is O(n).
The rule only applies to repeats inside the window. A character that was seen before left is no longer in the window, so it does not move left. That is why the earlier occurrence has to be checked against left, not just against whether the character was ever seen.
Trace on abcabb (hypothetical input, worked by hand)
| i | char | repeat inside window at | left after | window | best |
|---|---|---|---|---|---|
| 0 | a | none | 0 | a | 1 |
| 1 | b | none | 0 | ab | 2 |
| 2 | c | none | 0 | abc | 3 |
| 3 | a | index 0 | 1 | bca | 3 |
| 4 | b | index 1 | 2 | cab | 3 |
| 5 | b | index 4 | 5 | b | 3 |
Answer: 3.
Alternatives. A brute force over all substrings is O(n²) or worse. A set-based window that shrinks left one step at a time is also O(n), but each repeat costs extra steps. Jumping left reads each index once.
Failure mode to name. Moving left backward when the earlier occurrence is outside the window. On abba, the second a sits at index 3 and the old a at index 0 lies before left = 2. Jumping to 1 would put the first b back into the window and give the wrong length. Checking j >= left before jumping prevents this.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-3A config validator receives a JSON-like document in 4 KB chunks. It must reject the first bad closer with a byte offset, skip brackets inside string literals, and cap nesting at 512. What state do you carry between chunks, and how do you decide the verdict at end of stream?
The 90-second answer
The stack still holds the only structural information that matters, but the rules around it now interact. Three pieces of state must survive chunk boundaries: the opener stack, whether the scanner is inside a string literal, and whether the previous byte was a backslash inside that string. Losing any one of them breaks a case that a per-chunk check would accept. Rejection happens at the first closer that does not match the stack top, or at the first push that would exceed depth 512. The verdict at end of stream needs two checks: an open string is invalid even when the stack is empty, and a non-empty stack is invalid even when no string is open.
Why string state changes the answer. A ] inside "a]b" must not touch the stack. So the scanner has to know whether it is in a string before it interprets any bracket. An escape flag is needed because \" closes nothing: the backslash consumes the next byte. If the chunk ends right after a backslash, the flag must persist into the next chunk, or the first byte of that chunk is misread.
PAIRS = {')': '(', ']': '[', '}': '{'}
OPEN = set('([{')
MAX_DEPTH = 512
class Scanner:
def __init__(self):
self.stack = []
self.in_str = False
self.esc = False
self.offset = 0 # byte offset of the next byte
def feed(self, chunk: bytes):
for b in chunk:
pos = self.offset
self.offset += 1
if self.in_str:
if self.esc:
self.esc = False
elif b == 0x5C: # backslash
self.esc = True
elif b == 0x22: # quote
self.in_str = False
continue
if b == 0x22:
self.in_str = True
continue
ch = chr(b) # bytes >= 0x80 are UTF-8 continuation or lead bytes, never structural
if ch in OPEN:
if len(self.stack) == MAX_DEPTH:
raise ValueError(('too_deep', pos))
self.stack.append(ch)
elif ch in PAIRS:
if not self.stack or self.stack[-1] != PAIRS[ch]:
raise ValueError(('mismatch', pos))
self.stack.pop()
def finish(self):
if self.in_str:
return ('unterminated_string', self.offset)
if self.stack:
return ('unclosed', self.offset)
return NoneTrace on the chunks [b'{"k": "x\\', b'"]"}']. After chunk 1 the stack is {, in_str is True, and esc is True because the backslash is the last byte. Chunk 2 starts with ". The escape flag swallows it, so the string stays open. The ] is inside the string and is ignored. The final " closes the string, } pops {, and finish() returns None. Without the carried esc flag, the leading quote would close the string early and the ] would be treated as a closer on the stack {, which is a false rejection at the wrong offset.
Failure modes to test:
- Offsets reported in characters rather than bytes. The function above reports byte offsets, so a client can seek into the original payload. Mixing the two produces errors that point at the wrong place once the document contains multi-byte UTF-8.
- Depth cap conflated with mismatch. Returning the same error for
too_deepandmismatchsends clients down the wrong fix path. Keep the codes distinct. - A stream that ends with an open string and an empty stack. A check that only looks at the stack returns valid for
{"a": "unterminated? No: the stack is non-empty there, but for"abcalone the stack is empty and onlyin_strreveals the error. - Reading the whole body before validating. Early rejection is the reason for streaming. Buffering 50 MB before the first check turns a cheap rejection into a memory spike.
The per-byte loop is O(n) in time. Space is O(min(depth, 512)) for the stack, which is the point of the cap: it bounds memory on hostile input regardless of document size.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-4Walk me through merging a list of closed integer intervals. What does sorting cost, how do you test whether the next interval overlaps the current one, and why is the sweep after sorting linear in the input size?
The 90-second answer
Sort by start. That costs O(n log n) comparisons, and it dominates everything else. After that, one left-to-right pass keeps a current merged interval [s, e]. For each next interval [a, b], they overlap exactly when a <= e, because the sort guarantees s <= a. If they overlap, extend the end to max(e, b). If not, emit [s, e] and start a new one. The pass touches each input once, so after sorting the work is O(n).
Assumptions: intervals are closed, so [1,4] and [4,5] share the point 4 and merge. If your domain treats touching as separate, change <= to <. Use max, not b, because a long interval can swallow the next several.
def merge(intervals):
intervals.sort(key=lambda iv: iv[0])
out = []
for a, b in intervals:
if out and a <= out[-1][1]:
out[-1][1] = max(out[-1][1], b)
else:
out.append([a, b])
return outTrace on [[1,3],[2,6],[8,10],[15,18]], all hypothetical sizes: sorted order is unchanged. [1,3] starts out. [2,6]: 2 <= 3, so the end becomes max(3,6)=6. [8,10]: 8 > 6, new entry. [15,18]: 15 > 10, new entry. Result [[1,6],[8,10],[15,18]], three outputs from four inputs.
What the output size does and doesn't bound. The loop runs n times whatever the output looks like, so the output size m does not bound the scan. It bounds what you write and store: m appends, and n − m merges that each extend an existing entry. Auxiliary space beyond the output is O(1) if you sort in place and merge in place, and the output itself is at most n entries. When the output is much smaller than the input, you are mostly paying for the sort, not the sweep.
Failure modes to name. Sorting by end instead of start breaks the invariant s <= a, and the overlap test then silently drops intervals. Assigning out[-1][1] = b instead of max loses coverage when one interval contains another, and tests with nested input like [[1,10],[2,3]] catch it. Mutating the caller's list is a surprise in shared code; copy first if the caller reuses it.
Alternatives. If intervals arrive already sorted from a stream, skip the sort and the sweep runs online with O(m) memory. If you only need the total covered length and the coordinates are small integers, a difference array over the coordinate range is O(C) and avoids sorting, but it stops working once the range is large or sparse.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-5You need the k most frequent elements from an integer array of up to 10^6 items, and k can be anywhere from 1 to the number of distinct values. Compare a size-k min-heap with bucket sort: what does each cost, and when would you pick one over the other?
The 90-second answer
First I'd confirm the inputs: n up to 10^6, values are integers, and k is small relative to the number of distinct values. Then I'd build the frequency map in one pass with a hash map, O(n) time and O(d) space, where d is the number of distinct values. The two approaches differ only in how they pick the top k from that map.
A size-k min-heap keeps the k highest-frequency pairs seen so far. The root is the smallest frequency in the heap. For each distinct value with count c, if the heap has fewer than k entries I push; otherwise I push only when c exceeds the root, and then pop the root. Cost is O(d log k) time and O(k) extra space beyond the map.
Bucket sort indexes buckets by frequency. Counts are at most n, so I make n+1 buckets, put each value into bucket[count], then walk from the highest bucket down, collecting until I have k values. Cost is O(n) time and O(n) space for the buckets, and the walk stops early once k are collected.
My default at these sizes is the heap when k is small, because O(d log k) with k around 10 is close to linear and the memory stays at O(k) beyond the map. I switch to buckets when k is large or when I need the output unordered and fast, since bucket sort's bound does not depend on k.
Worked trace
Input [1,1,1,2,2,3], k = 2. Frequencies: 1→3, 2→2, 3→1.
| Step | Value | Count | Heap (min at root) | Action |
|---|---|---|---|---|
| 1 | 1 | 3 | [(3,1)] | size < k, push |
| 2 | 2 | 2 | [(2,2),(3,1)] | size = k, push |
| 3 | 3 | 1 | [(2,2),(3,1)] | 1 is not greater than root 2, skip |
Result: [1,2].
Bucket version for the same input: bucket[3]=[1], bucket[2]=[2], bucket[1]=[3]. Walk from index 3 down: collect 1, then 2, stop at k = 2.
Trade-offs and failure modes
- Heap with a comparator on frequency only. Ties are resolved by heap order, so the result is valid but not deterministic. If the spec requires a stable answer, add the value as a tie-breaker.
- Bucket sort memory. With n = 10^6 and all values distinct except one, the bucket array is a million slots mostly empty. Allocate lazily or cap buckets at the max observed frequency.
- Heap with k close to d. Pushes and pops still cost log k each, so the heap buys nothing over sorting the map entries, O(d log d). Say so if asked.
- Quickselect is the third option: O(d) average, O(d^2) worst case without a randomized pivot. Mention it, then note that it mutates the array of pairs and gives no worst-case guarantee.
What I'd check in a code review: the heap must be bounded at k on every push, otherwise memory grows to d and the bound silently becomes O(d log d).
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-6In an LRU cache, what data structure combination gives O(1) get and put, and why does each part exist?
The 60-second answer
Use a hash map from key to node, plus a doubly linked list ordering the nodes by recency. The most recently used node sits at the head, the least recently used at the tail. The map gives O(1) lookup of any key. The list gives O(1) move-to-front and O(1) eviction from the tail, provided you already hold the node pointer. Neither structure alone does both: a map has no recency order, and a list has O(n) lookup by key.
The list has to be doubly linked. Removing a node from the middle requires its predecessor, and a singly linked list would force a scan to find it.
Operations
get(k): look up the node in the map. If absent, return miss. If present, unlink it and splice it at the head.put(k, v): if the key exists, update the value and move the node to the head. Otherwise create a node, insert it at the head, record it in the map, and if size exceeds capacity, remove the tail node and delete its key from the map.
class LRU:
def __init__(self, cap):
self.cap = cap
self.map = {}
self.head = Node(); self.tail = Node() # sentinels
self.head.next, self.tail.prev = self.tail, self.head
def _unlink(self, n):
n.prev.next, n.next.prev = n.next, n.prev
def _push_front(self, n):
n.prev, n.next = self.head, self.head.next
self.head.next.prev = n
self.head.next = n
def get(self, k):
n = self.map.get(k)
if n is None:
return -1
self._unlink(n); self._push_front(n)
return n.val
def put(self, k, v):
n = self.map.get(k)
if n:
n.val = v
self._unlink(n); self._push_front(n)
return
if len(self.map) == self.cap:
lru = self.tail.prev
self._unlink(lru); del self.map[lru.key]
n = Node(k, v); self.map[k] = n; self._push_front(n)Sentinel head and tail nodes remove the empty-list and single-node special cases, which is where most bugs in interview implementations come from.
Trace (capacity 2, hypothetical sequence)
| Step | Op | List (MRU to LRU) | Result |
|---|---|---|---|
| 1 | put(1,A) | 1 | |
| 2 | put(2,B) | 2, 1 | |
| 3 | get(1) | 1, 2 | A |
| 4 | put(3,C) | 3, 1 | evicts 2 |
| 5 | get(2) | 3, 1 | -1 |
Thread safety
The structure is not safe under concurrent access as written, because every get mutates the list. Options, in increasing cost:
- A single mutex around both operations. Simple and correct. Throughput is capped by one lock, so it suits modest contention.
- Shard the cache into N independent LRUs keyed by hash, each with its own lock. Recency becomes per shard, not global, which changes eviction behaviour. State that trade-off explicitly.
- Lock-free approximations, such as CLOCK or sampled LRU, that avoid list mutation on reads. You give up exact LRU order.
A get that only needs to check presence can take a read lock, but a true LRU get writes, so a read-write lock does not help here. Java's LinkedHashMap with accessOrder=true gives you the same structure, and wrapping it in Collections.synchronizedMap or an explicit lock is the usual production answer. Mention that you would reach for the library before writing this yourself.
Failure modes to name
- Forgetting to update the map when evicting, leaving a stale key that returns a dangling node. Detect with a test that fills past capacity and then checks
len(map) == cap. - Updating the list without the lock under contention, which corrupts pointers and shows up as a loop in
getor lost entries. Detect with a stress test that runs random operations across threads and checks the list length against the map size at the end. - Sharding with a hot key: one shard saturates and its lock dominates p99 latency. Measure per-shard hit and lock-wait counts before choosing shard count.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-7The grid is 4000 by 4000, memory-mapped read-only, and you must return the island count and the largest island's size in one pass. Which traversal do you use, what visited state do you keep, and how much memory peaks on an all-land grid?
Opening answer
I'd use BFS with a bitset for visited state, mark on push, and a counter for the current island's size. The read-only mapping rules out in-place marking, so the visited state has to live beside the grid. Memory is then dominated by the bitset, not the traversal.
Visited state. Sixteen million cells as bits is 16,000,000 / 8 = 2,000,000 bytes, about 1.9 MiB. A bytearray with one byte per cell is 16 MB, eight times larger. Index the bit as r * C + c, and do the test and set in one step so you never read a cell twice.
Why BFS and not DFS here. Both visit each cell once, so time is O(R·C) either way. The difference is how far the container grows. With mark-on-push, a BFS queue on an open grid holds one wavefront. From a single source on an all-land grid, the cells at Manhattan distance d form a diagonal of min(d+1, 4000, 7999-d) cells, peaking at 4000 near the far corner. So the queue never exceeds about 4000 entries, roughly 4000 tuples at about 64 bytes each, around 250 KB.
An iterative DFS with mark-on-push has no such bound. Each pop can push up to three new cells, and the stack holds the unexplored branches of a spanning tree that can be deep and wide at once. On a serpentine or all-land grid it can reach a large fraction of R·C entries. The explicit stack avoids the recursion limit but not the memory growth, so it is the wrong default here.
Trace. On a 3 by 3 grid of 11., 1.., ..1 with the scan starting at (0,0): the bit for (0,0) is set when the cell is pushed, the queue holds (0,0), size counter reaches 1. Pop it and push (0,1) and (1,0), setting their bits, size reaches 3. Pop both and push nothing new. The island closes with size 3, and the counter is recorded as the island's answer. The scan then finds (2,2), a new island of size 1. Final: count 2, largest 3.
Counter state. Keep current as a local that resets per BFS start, and best = max(best, current) after each island. Increment current at push time, not pop time, so the count matches the cells marked.
Failure modes. Marking on pop lets a cell enter the queue several times before it is popped, and on dense land the queue can then grow to several times 4000 entries. Bounds checks after the index calculation read the wrong neighbour on the last column because r * C + c + 1 wraps into the next row. Check c + 1 < C explicitly. Ragged rows break R * C, so validate width per row before building the bitset.
When not to use this. If the grid can be copied, a bytearray copy with in-place marking is simpler and avoids the bit arithmetic. If the rows arrive as a stream and you cannot keep the grid at all, union-find over the previous row's labels is the right shape.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-8You're given numCourses and prerequisite pairs [a, b], where b must come before a. How would you detect whether the schedule is impossible because of a cycle, and when would you pick Kahn's algorithm over DFS with three-colour marking?
Core answer (about 90 seconds)
First I'd fix the model: a directed graph with V courses and E edges, where an edge u to v means u must come before v. Building the adjacency list and indegree array costs O(V+E) time and O(V+E) space. Both algorithms are linear, so the choice comes down to what else I need from the run.
Kahn's algorithm. Compute indegrees, seed a queue with every node whose indegree is 0, pop a node, and decrement the indegree of each successor, enqueuing any that reach 0. If the number of popped nodes is less than V, the remaining nodes never reached indegree 0, so a cycle exists. The popped order is a valid topological order, which is the schedule itself.
DFS with three colours. WHITE means unvisited, GREY means on the current recursion path, BLACK means finished. An edge into a GREY node is a back edge, and a back edge means a cycle. A node turns BLACK when its DFS returns and is never revisited.
I'd pick Kahn when I need the schedule and the cycle check in one pass, and when stack depth is a risk. A 10^5-long prerequisite chain overflows a recursive DFS under CPython's default recursion limit of 1000. I'd pick DFS when I need to name a cycle, since the GREY path on the stack is the cycle, and when I want to stop at the first back edge.
from collections import deque
def can_finish_kahn(n, edges):
adj = [[] for _ in range(n)]
indeg = [0] * n
for u, v in edges:
adj[u].append(v)
indeg[v] += 1
q = deque(i for i in range(n) if indeg[i] == 0)
done = 0
while q:
u = q.popleft()
done += 1
for v in adj[u]:
indeg[v] -= 1
if indeg[v] == 0:
q.append(v)
return done == nTrace (Python 3.12, n=4, edges 0→1, 1→2, 2→1, 3→0). Indegrees are [1, 2, 1, 0]. Queue starts as [3]. Pop 3, done=1, indeg[0] drops to 0 and 0 is queued. Pop 0, done=2, indeg[1] drops to 1, nothing queued. Queue empty. done=2 is not 4, so the answer is no. Nodes 1 and 2 form the cycle; node 0 is stuck downstream of it only in the sense that it was processed before the cycle was reached, so the leftover set is exactly {1, 2}.
| Kahn | DFS three-colour | |
|---|---|---|
| Output | topological order | cycle path from GREY stack |
| Recursion | none | depth up to V |
| Early exit | no | yes, on first back edge |
| Leftovers | all nodes that never reach indegree 0 | not applicable |
Failure modes. Duplicate edges are harmless in Kahn if you count indegree per edge and decrement per edge. A self-loop (a, a) keeps indegree at least 1, so Kahn reports a cycle correctly. The common DFS bug is treating any revisit as a cycle instead of only GREY revisits; that gives false positives on diamond-shaped graphs such as 0→1, 0→2, 1→3, 2→3. I'd catch both with a diamond test and a 10^5 chain test before trusting either version.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-9A routing service runs Dijkstra on a road graph using a binary heap. Why is greedy settling correct only when edge weights are nonnegative, what does a run cost in big-O terms, and when would you switch to Bellman-Ford?
The 90-second answer
Dijkstra settles vertices in order of tentative distance. When the cheapest frontier vertex is popped, its distance is final, because every other path to it must leave the settled set through some frontier vertex, and that vertex already has distance at least as large. Adding a further edge can only add a nonnegative amount, so nothing can undercut the popped value. A single negative edge breaks the last step: a later path can gain back what it spent.
With a binary heap the cost is O((V + E) log V), which is O(E log V) for any connected graph since E ≥ V − 1. I would use lazy deletion: push a new entry on each successful relaxation and skip stale entries on pop. The heap then holds up to E entries, and log E is O(log V) because E ≤ V².
Counterexample with negative weight
| Step | Settled | Heap pop | Tentative distances |
|---|---|---|---|
| init | none | S:0 | S=0, A=∞, B=∞ |
| 1 | S | A:2 | A=2, B=5 |
| 2 | A (wrong) | B:5 | A=2 final, B=5 |
| later | B relaxes A to 5−4=1 | A should be 1 |
Edges: S→A = 2, S→B = 5, B→A = −4. Dijkstra settles A at 2 before it ever sees the path S→B→A = 1. Once A is settled, the relaxation that would fix it is skipped.
When Bellman-Ford is needed
Bellman-Ford relaxes every edge V−1 times, for O(VE). It is correct with negative weights and reports a negative cycle if a V-th pass still relaxes something. Use it when:
- Edges can be negative, such as currency arbitrage or costs with rebates.
- You need to detect a negative cycle.
- The graph is small or the scan is cheap. For V = 10⁴ and E = 10⁵ it is about 10⁹ relaxations, which is too slow for a per-request path.
If you need all-pairs distances with negative edges, reweight with Johnson's algorithm: one Bellman-Ford from a virtual source, then Dijkstra from each vertex. That gives O(VE + V(V + E) log V).
Failure mode I would watch for
A silent negative weight, often a float subtraction that rounds below zero or a mis-signed travel-time delta, does not crash Dijkstra. It returns a plausible but wrong route. I would validate weights at ingest and assert nonnegativity in tests with a generated graph.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-10In Word Search II, what data structure do you build from the word list so one DFS per grid cell can match every word, and what condition lets you cut a branch early?
The 60-second answer
Build a trie from the word list. Then run one DFS from each grid cell, walking the trie alongside the grid path. A branch is cut the moment the letters spelled so far have no child in the current trie node, because no word can extend that path. A node flagged as the end of a word means that word has been spelled, so it is reported.
The point is that one walk serves every word. Running a separate search per word repeats the same grid walks for each word. With the trie, a path spelling oa is explored once, and it is shared by oat, oath and oaths.
Hypothetical figures: a 12 x 12 grid (144 cells), 10^4 words, maximum word length 10, 4 neighbours per cell. A search per word starts 10^4 x 144 walks. The trie version starts 144 walks, one from each cell, and each walk stops as soon as its letters leave the trie.
Trace on the grid o a / a t with words oat, oath, tea. The trie is o-a-t (end of oat), then h (end of oath), and a separate t-e-a branch for tea.
- Start at (0,0)
o. The root has anochild, so the walk continues. - Step to (0,1)
a. Nodeoaexists. - Step to (1,1)
t. Nodeoatis marked as a word, sooatis reported. - From (1,1), the neighbour (1,0)
ahas no child underoat(onlyhdoes). Cut. - Start at (0,1)
a. The root has noachild. Cut in one lookup. - Start at (1,1)
t. Nodetexists, but no neighbouraextends it tota. Cut.teais never found because the grid has noe.
Only a few trie nodes are checked across all 144 starts.
Details that decide whether it works
Clear the end-of-word flag after reporting a word, so a word appearing in several places is returned once. Mark each cell as visited before recursing and unmark it on backtrack. Forgetting the unmark step gives false matches when a letter repeats.
A dictionary child map per node is simpler than a 26-slot array, but slower when the alphabet is fixed to lowercase letters.
Test with a word list containing duplicates, a grid where one letter repeats everywhere, and a word that is a prefix of another. Those cases catch missed words, repeated output and the unmark bug.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-11A dictionary trie holds 2 million keys, first over lowercase ASCII and then over full Unicode. Compare giving each node a fixed child array against a per-node hash map. Where does each win on memory, and what would you do for Unicode?
The 90-second answer
Assume 64-bit pointers. A child array costs the same whatever the node holds, so it wins on dense nodes. A hash map costs per child, so it wins on sparse ones. For 26 lowercase letters, an array is 26 × 8 = 208 bytes per node whether the node has one child or twenty-six. For Unicode, a fixed array is not an option: 0x10FFFF code points × 8 bytes is about 8.9 MB per node. So Unicode forces a sparse representation, and the real decision is how to find a child in a node that has one or two.
The figures below are hypothetical. They assume a hash entry costs 40 bytes including bucket overhead and an empty map header costs 48 bytes. Measure your runtime before relying on them.
| Children in node | Child array (26 slots) | Hash map |
|---|---|---|
| 1 | 208 B | 48 + 40 = 88 B |
| 3 | 208 B | 48 + 3 × 40 = 168 B |
| 26 | 208 B | about 1.1 KB, plus table slack |
Dictionary tries are mostly sparse. Most nodes sit deep in the trie with one or two children, so a per-node map wins in aggregate. A map still costs a header, a pointer dereference and GC pressure on every node, and its resize spikes show up in tail latency under insert bursts. The usual answer is an array for the top one or two levels, where fan-out is high, and compact children below.
For Unicode, fan-out is set by the characters actually observed under a prefix, and for most prefixes it stays small. The options, in order of preference:
- Compress the trie first. Radix or Patricia form collapses single-child chains, so most nodes disappear. This often saves more memory than any choice of child container.
- Store small fan-out as sorted parallel arrays: a uint32 codepoint array and a child pointer array. Scan linearly or binary-search. That is about 12 bytes per child and no per-node hash header.
- Promote to a hash map only above a threshold, around 8 to 16 children. Tune this from your key distribution.
- A byte-level trie over UTF-8 caps fan-out at 256 per byte. A character can take up to 4 hops, and a 256-slot array is 2 KB per node, so this still needs the compact children above.
Failure modes and detection
- A per-node map in Java or Python carries object overhead that a plain array does not. Detect it with tracemalloc, a heap dump, or JOL for Java, not with a guess.
- An ASCII array trie holding a million mostly sparse nodes wastes most of its slots. Detect it by dividing RSS by key count and comparing against the sum of child slots actually used.
- A hash map under insert bursts pauses while it resizes. Watch p99 insert latency during warmup, not only throughput.
Decision
For lowercase ASCII, use arrays on the dense top levels and a compressed radix trie below. For Unicode, use compressed nodes with small sorted arrays, promoting to a hash map past the threshold. Confirm both with measured bytes per key on a sample of your real keys.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-12Your input is a multiset of integers such as [1, 2, 2, 3], and you need every distinct subset. Compare plain index-based backtracking with the version that sorts first and skips repeated values at the same tree level. What changes in the recursion, and how does each version's work relate to the number of distinct answers?
The 90-second answer
Plain backtracking treats each index as a yes/no choice. For n elements that builds 2^n index subsets, and when values repeat, many of them are the same value subset. Sorting and skipping changes the tree, not the output rule: at each call I try candidates from start onward, and if nums[j] == nums[j-1] with j > start, I skip j. That skip removes sibling branches that would produce a subset already emitted by an earlier sibling. Nothing else in the recursion changes.
def subsets_plain(nums):
out = []
def dfs(i, path):
if i == len(nums):
out.append(path[:])
return
dfs(i + 1, path)
path.append(nums[i])
dfs(i + 1, path)
path.pop()
dfs(0, [])
return out
def subsets_dedup(nums):
nums = sorted(nums)
out = []
def dfs(start, path):
out.append(path[:])
for j in range(start, len(nums)):
if j > start and nums[j] == nums[j-1]:
continue
path.append(nums[j])
dfs(j + 1, path)
path.pop()
dfs(0, [])
return outTrace on [1, 2, 2] (already sorted):
| node | path | children tried | effect |
|---|---|---|---|
| root | [] | j=0 (1), j=1 (2), j=2 (2) | j=2 skipped, since it equals j=1 and j > start |
| after 1 | [1] | j=1 (2), j=2 (2) | j=2 skipped, same reason |
| after 2 (j=1) | [2] | j=2 (2) | allowed, because j == start |
Output: [], [1], [1,2], [2], [1,2,2], [2,2]. Six distinct subsets. Plain backtracking would emit eight index subsets, including two copies of [2] and two of [1,2].
Cost. Plain backtracking makes exactly 2^n leaf calls, whatever the duplicates. The dedup version does one call per emitted subset, so its call count equals the number of distinct value subsets k, and each call scans its siblings. With all values equal, say ten 1s, plain produces 1024 emits for 11 answers. Dedup produces 11.
Trade-off. Dedup requires a sort, O(n log n), and it only works if equal values are adjacent after sorting. Plain needs no sort and no comparisons, which makes it simpler when values are unique or when the caller needs index subsets rather than value subsets. The dedup version also gets a harder-to-see bug risk: changing j > start to j > 0 drops valid subsets such as [2,2], because the guard is what allows a repeated value deeper in one path while forbidding it as a second sibling.
What I'd check: that path[:] copies on emit, and that the input really is sorted before the skip rule is applied. Without sorting, the adjacency test silently misses duplicates.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-13Your N-Queens counter is correct but slows down past n=12. Explain how column and diagonal sets prune the search, what bitmasks buy you per node, and why the search is still exponential even with pruning.
Short answer. Carry three masks down the recursion: cols (columns used), d1 (anti-diagonals already attacked, shifted into the current row), and d2 (main diagonals, shifted the other way). A square is safe when its bit is clear in all three. The pruning removes dead branches early, but the search still branches up to n ways per row, so the worst case stays exponential.
Assumptions: count all solutions, n is at most 64 so the masks fit in a 64-bit word, and the code is Python 3.12 (C or Java need the same masking with unsigned or long types).
def count_queens(n):
full = (1 << n) - 1
def go(cols, d1, d2):
if cols == full:
return 1
avail = full & ~(cols | d1 | d2)
total = 0
while avail:
bit = avail & -avail
avail ^= bit
total += go(cols | bit, ((d1 | bit) << 1) & full, (d2 | bit) >> 1)
return total
return go(0, 0, 0)Trace for n=4, first queen in column 0. cols=0001, d1=0010, d2=0000. The next row has avail = 1111 & ~0011 = 1100, so columns 2 and 3 are legal. Column 1 is removed by the diagonal shift, column 0 by the column mask. Each bit & -avail extracts the lowest legal column in O(1), so a node costs work proportional to its safe squares rather than to n.
Sets versus bitmasks. The set-based version uses boolean arrays for columns, r+c and r-c indexed by 2n-1 slots. That is also O(1) per check, but each check is a load and a branch. The mask version computes every legal square of a row with three ORs and one negation, then iterates only over survivors. The masks also avoid allocation and hashing, and the recursion depth is n with O(n) stack. Masks cap n at the word width, which is the trade-off.
Why it stays exponential. Without pruning, the row-by-row tree has at most sum over k of n!/(n-k)! partial placements, which is about e·n!. Pruning cuts that down but gives no polynomial guarantee: every solution is a leaf, and the solution count itself grows superpolynomially. For n=8 there are 92 solutions; for n=15 there are 2,279,184. Any algorithm that enumerates solutions pays for each one, and counting has no known polynomial method.
Failure modes. Dropping the & full after the left shift of d1 lets bits above column n-1 look legal, so the solver indexes past the board and overcounts. Check n=8 against 92 and n=6 against 4 to catch it. In C, avail & -avail on a signed type is undefined for the minimum value, so use unsigned.
When to change approach. To find one solution quickly for large n, use min-conflicts local search, which is not exhaustive and cannot count. To count for n beyond the low twenties, you need a different method entirely; the mask search is for the exact enumeration this size.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-14In the coin change DP over a fixed amount, which direction does the amount loop run for unbounded coins versus 0/1 coins, and why?
The 90-second answer
Both versions use dp[x], the fewest coins that make amount x, with dp[0] = 0 and every other entry starting at infinity. The only difference is the direction of the inner amount loop. For unbounded coins (each denomination reusable), iterate x upward from coin to amount. For 0/1 coins (each used at most once), iterate x downward from amount to coin. What matters is what dp[x - coin] holds when it is read. Going up, dp[x - coin] may already include this same coin, so the coin can be chosen again. Going down, dp[x - coin] still reflects only the earlier coins, so each coin is used at most once.
The cost is O(n * amount) time for n coins and O(amount) space, because each coin makes one pass over the amount array.
# unbounded: upward
for c in coins:
for x in range(c, amount + 1):
dp[x] = min(dp[x], dp[x - c] + 1)
# 0/1: downward
for c in coins:
for x in range(amount, c - 1, -1):
dp[x] = min(dp[x], dp[x - c] + 1)Trace, unbounded. coins = [2, 5], amount = 7. After coin 2: dp[2]=1, dp[4]=2, dp[6]=3. After coin 5: dp[5]=1, and dp[7] = min(inf, dp[2] + 1) = 2, which is 5 + 2. Answer 2.
Trace, 0/1. Same coins, same amount, downward loops. After coin 2 only dp[2]=1 is set, because dp[4] and dp[6] read entries that are still infinity. After coin 5, dp[7] = min(inf, dp[2] + 1) = 2, which is 2 + 5 with each coin used once. Answer 2 again, so this input does not separate the two versions.
A case that does: coins = [2], amount = 4. Unbounded gives dp[4] = 2 (2 + 2). The 0/1 loop never reads a value set by the same coin, so dp[4] stays infinity and the answer is -1. That is the behaviour to state if the interviewer asks what each variant returns.
Loop order also changes what is counted. The outer loop over coins with an inner amount loop counts combinations, where [1,2] and [2,1] are one way. Swapping the two loops counts ordered sequences instead. Candidates often get this backwards, so state it if the interviewer asks for the number of ways rather than the minimum count.
When not to use this. If the amount is large but the coin count is small, the O(n * amount) table is wasteful. A common failure: an unreachable amount keeps the infinity sentinel, and the code must return -1 rather than that value.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-15Return the length of a longest strictly increasing subsequence of up to 200,000 integers, and among all of them the lexicographically smallest one, in O(n log n) time. Walk me through how you compute it and why the tie-break still holds.
The 90-second answer
First I'd fix the semantics. Strictly increasing, so [2, 2] has length 1. Lexicographically smallest compares the values left to right, so [1, 4, 5, 6] beats [3, 4, 5, 6]. Values fit in 32-bit signed integers.
The length alone is patience sorting: tails[k] is the smallest tail of an increasing run of length k+1, and lower_bound on each element gives the pile. But the lexicographic requirement needs more than the forward pass, because the forward pass fixes what ends a run, not what starts one. So I need, for each index i, L[i], the length of the longest increasing subsequence starting at i.
Get L from a second patience pass. Walk the array right to left and feed the negated values into the same strict patience routine. The pile an element lands in, plus one, is L[i]. Negation turns a run that increases left to right into one that increases in reverse order, so the pass is the same code with a different input.
With L in hand, build the answer greedily from the left. Let need start at max(L), the last chosen index last_i = -1, and the last chosen value last_v = -inf. At each step, among indices j > last_i with a[j] > last_v and L[j] == need, take the smallest value, breaking ties by the smallest index.
Why L[j] == need is the right filter: if L[j] > need, the chosen prefix plus that chain would be longer than the maximum, which is impossible. So any feasible j has L[j] == need exactly. Why the tie-break on index: among equal values at the same level, the earlier index leaves a superset of options for the rest of the sequence, so it can never be worse.
Complexity: the level lists are disjoint and need only decreases, so each level is scanned once. Total scan work is O(n), and the whole thing is O(n log n) with the two patience passes dominating.
Trace on a = [3, 1, 4, 1, 5, 9, 2, 6]. The L values by index are [4, 4, 3, 3, 2, 1, 2, 1]. Max is 4. Level 4 holds indices 0 and 1. Step 1: smallest value is 1 at index 1. Level 3 holds indices 2 and 3. Index 2 (value 4) is after index 1 and larger than 1. Pick 4. Level 2 holds indices 4 and 6. Index 4 (value 5) qualifies. Pick 5. Level 1 holds indices 5 and 7. Index 7 (value 6) is the smallest value above 5 after index 4. Result: [1, 4, 5, 6].
Failure modes
- Taking the smallest value without the index filter gives
[1, 2, 6]-style answers that are shorter thanneedand then fail at the end. Testing the length of the output catches it. - Using the forward
prevchain for reconstruction produces a valid LIS, but not necessarily the lexicographically smallest one, because the chain is fixed by the first arrival at each pile. - A tie-break on the largest index looks symmetrical and is wrong, since it can strand the remaining levels.
Check
Compare against an O(n^2) brute force on random arrays of length 12 with values in 0 to 5, which produces many ties. Those cases exercise every tie-break branch.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-16Two strings of lengths 2,000 and 3,000 need an edit distance but not the alignment. Write the recurrence, say what the full table costs in memory, and show how you cut it to one row without losing the answer.
Opening answer
Let D[i][j] be the minimum number of insertions, deletions and substitutions that turn the first i characters of a into the first j characters of b. Base cases: D[i][0] = i and D[0][j] = j. For i, j >= 1:
- if
a[i-1] == b[j-1], thenD[i][j] = D[i-1][j-1] - otherwise,
D[i][j] = 1 + min(D[i-1][j], D[i][j-1], D[i-1][j-1])
The three terms are delete, insert and substitute. Each cell reads only the row above and the cell to its left, so the full table is not needed when you only want the number.
Assumptions: unit costs for all three operations, and the answer is the distance only.
Full table cost for 2,000 by 3,000
The table has 2,001 by 3,001 cells, about 6 million. At 4 bytes per entry that is about 24 MB. Time is O(mn) either way, so reducing the space does not change the running time. A single row of 3,001 ints is about 12 KB.
Worked trace on a small case
cat to cut has distance 1 (substitute a with u). Columns are the characters of cut, rows are the characters of cat.
| c | u | t | ||
|---|---|---|---|---|
| 0 | 1 | 2 | 3 | |
| c | 1 | 0 | 1 | 2 |
| a | 2 | 1 | 1 | 2 |
| t | 3 | 2 | 2 | 1 |
Some cells, checked by hand:
D[1][1]:c == c, so it copiesD[0][0] = 0.D[2][2]:a != u, so it is1 + min(D[1][2]=1, D[2][1]=1, D[1][1]=0), which gives 1.D[3][3]:t == t, so it copiesD[2][2] = 1. This is the answer.
One-row version
Overwriting the row in place destroys D[i-1][j-1] before it is read, so the code keeps the old diagonal in a scalar and the old row[j] in up before writing it:
def edit_distance(a, b):
m = len(b)
row = list(range(m + 1))
for i, ca in enumerate(a, 1):
diag = row[0] # old D[i-1][j-1] for j = 1
row[0] = i
for j, cb in enumerate(b, 1):
up = row[j] # old D[i-1][j]
row[j] = min(up + 1, row[j - 1] + 1, diag + (ca != cb))
diag = up
return row[m]Tracing cat/cut through this code gives the same bottom-right value, 1, as the table above.
Trade-off
The one-row version returns only the distance. If the interviewer wants the edit script, you need the full table to backtrack, or Hirschberg's divide-and-conquer, which keeps O(min(m, n)) space at roughly twice the work. Put the shorter string in b so the row is as short as possible.
Failure modes
-
Reading
row[j-1]after it has been overwritten in the current row. The result looks plausible and is wrong for many inputs. Catch it with a brute-force comparison against the full table on short random strings. -
Forgetting the base column
row[0] = i. Thenrow[0]keeps its old value on every row and long deletions are undercounted. -
Forgetting to save the old diagonal before the first update in each row. The diagonal for
j = 1must come from the previous row'srow[0], which is why it is read beforerow[0]is set.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-17Count the right-or-down paths from the top-left to the bottom-right of an m by n grid where some cells are obstacles. Write the DP, then explain which boundary cases break naive code, and how a single rolling row changes the update order.
The 90-second answer
Let dp[i][j] be the number of valid paths from (0,0) to (i,j). If the cell is an obstacle, dp[i][j] = 0. Otherwise dp[i][j] = dp[i-1][j] + dp[i][j-1], where any neighbour outside the grid contributes 0. The base case is dp[0][0] = 1 unless (0,0) is an obstacle. The answer is dp[m-1][n-1], which is 0 when the destination itself is blocked. Time is O(mn). Memory is O(mn) as written, and O(n) once you roll it.
The bugs live in the boundaries, not the recurrence.
Boundary cases that break naive code
- Start or end cell is an obstacle. The recurrence still runs, but
dp[0][0]must be forced to 0, or every path count is inflated. - First row and first column. There is no
i-1orj-1neighbour. In Python,dp[i][-1]silently wraps to the last column and adds garbage. Guard the index explicitly. - Single row or single column. Both loops degenerate, and a 1x1 grid is the easiest case to get wrong: no obstacle gives 1, an obstacle gives 0.
- Overflow. For an empty 35 by 35 grid the count is C(68,34), about 2.8e19, which already exceeds a signed 64-bit integer. Say whether the problem wants the exact value or the result modulo a prime.
Rolling array
One row of length n is enough, because row i only reads row i-1 and the current row. Update in place from left to right:
def unique_paths(grid):
m, n = len(grid), len(grid[0])
dp = [0] * n
for i in range(m):
for j in range(n):
if grid[i][j] == 1:
dp[j] = 0 # must write, not skip
elif i == 0 and j == 0:
dp[j] = 1
else:
from_left = dp[j - 1] if j > 0 else 0
dp[j] = dp[j] + from_left # dp[j] still holds row i-1
return dp[n - 1]The subtle line is the obstacle branch. If you continue instead of writing 0, dp[j] keeps the value from row i-1 and the blocked cell leaks paths into the next row.
Trace
Grid 3x3, obstacle at the centre:
. . .
. # .
. . .Row 0: [1, 1, 1]. Row 1: j=0 gives 1+0=1; j=1 is blocked, so 0; j=2 gives 1+0=1. Row 1 is [1, 0, 1]. Row 2: j=0 gives 1; j=1 gives 0+1=1; j=2 gives 1+1=2. Answer 2. Check: 6 paths in an empty 3x3 grid, 4 of which pass through the centre, leaving 2.
When not to roll
If you need the paths themselves, or the cells on them, keep the full table or reconstruct backwards. Rolling discards the history you need to walk back.
Tests that catch the failures
Blocked start, blocked end, a blocked first row, a 1x1 grid with and without an obstacle, and a random grid compared against the 2-D version.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-18In Jump Game, where each value is the maximum jump length from that index and you start at index 0, what single number does the greedy scan keep as it moves left to right?
The 90-second answer
The greedy scan keeps reach, the farthest index reachable from index 0 so far. Scan left to right. If the current index i is past reach, it cannot be reached and the answer is false. Otherwise update reach = max(reach, i + nums[i]). If reach reaches or passes the last index, the answer is true. Because the scan never needs to remember which jump produced which index, one number is all it stores. The proof that this works is a short argument, and I can give it if you want it.
def can_jump(nums):
reach = 0
for i, step in enumerate(nums):
if i > reach:
return False
reach = max(reach, i + step)
if reach >= len(nums) - 1:
return True
return TrueTrace, [2, 3, 1, 1, 4]. i=0: reach=max(0,2)=2. i=1: reach=max(2,4)=4, which is the last index, so return true.
Trace, [3, 2, 1, 0, 4]. i=0: reach=3. i=1, 2, 3: reach stays 3. i=4: 4 > 3, so return false. The zero at index 3 is what blocks the path.
DP alternative. Define ok[j] as true if index j is reachable. For each j, check whether some earlier reachable i satisfies i + nums[i] >= j. That is O(n^2) time and O(n) space. The greedy gets O(n) time and O(1) space by tracking only reach.
When to pick which. Use the greedy for the yes/no question. Switch to DP or a level-based BFS when you need the minimum number of jumps or the actual path, since the single reach value discards which jump was taken.
Failure modes. Forgetting the i > reach check, which returns true for inputs with a zero in the middle that blocks the path. Also, a single-element array must return true, and a first element of 0 with length greater than 1 must return false. Test both.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-19Koko has up to 10^4 piles of up to 10^9 bananas and h hours, and her speed is capped at 10^9 per hour. Each pile is finished in whole hours with no hour shared between piles. Find the minimum speed, return -1 if even the cap fails, and show the hour total cannot overflow 64 bits.
The 90-second answer
First I check the cap. Feasibility at speed k is H(k) = sum(ceil(p / k)) <= h. H is nonincreasing in k, so feasibility is monotone: false below some threshold, true above it. That lets me binary search over [1, CAP], where CAP = 10^9. If H(CAP) > h, no legal speed works and I return -1. That one test covers two cases: h < n (each pile needs at least one hour, so H(k) >= n for every k) and piles too large for the cap. Nothing else needs a special branch.
Overflow is the part people miss. At k = 1, H equals the sum of all piles, at most 10^4 × 10^9 = 10^13. That fits in a signed 64-bit integer with room to spare, so the running total never needs 128-bit arithmetic. I still use the early exit, since it keeps the inner loop short when the answer is far from feasible.
def hours(piles, k, cap):
total = 0
for p in piles:
total += (p - 1) // k + 1 # ceil(p / k), integer only
if total > cap:
return total # infeasible, stop early
return total
def min_speed(piles, h, CAP=10**9):
if hours(piles, CAP, h) > h:
return -1 # cap fails, or h < len(piles)
lo, hi = 1, CAP
while lo < hi:
mid = (lo + hi) // 2
if hours(piles, mid, h) <= h:
hi = mid # feasible: answer <= mid
else:
lo = mid + 1 # infeasible: answer > mid
return loWorked trace. piles = [3, 6, 7, 11], h = 8, CAP = 11 for this example.
| lo | hi | mid | H(mid) | verdict | next |
|---|---|---|---|---|---|
| 1 | 11 | 6 | 1+1+2+2 = 6 | feasible | hi = 6 |
| 1 | 6 | 3 | 1+2+3+4 = 10 | infeasible | lo = 4 |
| 4 | 6 | 5 | 1+2+2+3 = 8 | feasible | hi = 5 |
| 4 | 5 | 4 | 1+2+2+3 = 8 | feasible | hi = 4 |
The loop ends at 4. Check: H(3) = 10 > 8, H(4) = 8 ≤ 8. Pre-check: H(11) = 4 ≤ 8, so the answer is not -1.
Failure modes to name.
- Floating-point ceil.
math.ceil(p / k)loses precision near 10^9 in double arithmetic in some languages.(p - 1) // k + 1avoids it. - Off-by-one in the update. Setting
hi = mid - 1on a feasible mid skips the answer. Keep the invariant that the answer lies in[lo, hi]. - Checking the wrong bound. Testing
H(max(piles))instead ofH(CAP)is wrong when the cap is below max(piles): the search then returns a speed the cap forbids. - Non-monotone variants. If the question asks for the speed that finishes in exactly h hours, feasibility can flip more than once and the boundary search answers a different question.
When not to use it. For many queries against different h on the same piles, precompute the sorted distribution or a prefix structure. For one query with small inputs, a linear scan over k is shorter and equally correct.
Verification. Compare against brute force on random small inputs, and include h = n (answer is max(piles)), a single pile, and h < n (answer is -1).
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-20Search a rotated sorted array for a target in O(log n). How do you decide which half is sorted at each step, and why does allowing duplicates break the O(log n) guarantee?
The 90-second answer
At each step, mid splits the window into two halves, and at least one of them is sorted in a rotated array with distinct values. Compare nums[lo] with nums[mid]. If nums[lo] < nums[mid], the left half [lo..mid] has no drop in it, so it is sorted. Otherwise the drop from the maximum to the minimum sits in (lo, mid], and the right half [mid..hi] is sorted. Check whether the target lies inside the sorted half's range. If it does, search that half. If not, search the other one. Each step discards half the window, so the search is O(log n).
Duplicates break the step that decides which half is sorted. When nums[lo] == nums[mid], the comparison tells you nothing: the segment could be all equal, or the drop could sit inside it.
# Python 3.12
def search(nums: list[int], target: int) -> bool:
lo, hi = 0, len(nums) - 1
while lo <= hi:
mid = (lo + hi) // 2
if nums[mid] == target:
return True
if nums[lo] == nums[mid]:
lo += 1 # undecidable: drop one copy and retry
continue
if nums[lo] < nums[mid]: # left half sorted
if nums[lo] <= target < nums[mid]:
hi = mid - 1
else:
lo = mid + 1
else: # right half sorted
if nums[mid] < target <= nums[hi]:
lo = mid + 1
else:
hi = mid - 1
return FalseTrace on [1, 0, 1, 1, 1], target 0:
| lo | hi | mid | values | action |
|---|---|---|---|---|
| 0 | 4 | 2 | 1, 1, 1 | equal at lo and mid, so lo = 1 |
| 1 | 4 | 2 | 0, 1, 1 | left sorted, 0 is in [0, 1), so hi = 1 |
| 1 | 1 | 1 | 0 | found |
Why the guarantee breaks. Take [1, 1, 1, 0, 1] and [1, 0, 1, 1, 1]. For both, lo, mid and hi hold the value 1, so the three endpoints look the same. In the first array the drop is in the right half. In the second it is in the left half. No comparison at this step separates them, so the code can only drop one copy and retry. If the array is mostly one repeated value with the single distinct value hidden among them, every step removes one index and the cost is O(n). The worst case is therefore O(n), not O(log n). Average behaviour on random input is still close to logarithmic, which is why the bound is stated as a worst case.
When distinct values hold. The bound is O(log n) only when the check nums[lo] == nums[mid] never fires, which means distinct values. With duplicates, the honest claim is O(log n) for distinct inputs and O(n) worst case in general. Finding the minimum has the same problem, so an interviewer who asks for a guarantee with duplicates should hear that the guarantee does not exist.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-21Reverse a singly linked list. Walk me through the three-pointer iterative loop and the invariant that makes it correct, then compare it with the recursive version. What does each cost in stack space for a list of 10^6 nodes?
The 90-second answer
I'd write the iterative version first. It keeps three pointers: prev, cur, and a saved nxt. Each step saves cur.next, points cur backwards at prev, then advances both pointers. It runs in O(n) time and O(1) extra space. The recursive version is shorter and reads well, but it uses one stack frame per node, so a 10^6-node list needs about 10^6 frames. That fails in CPython, where the default recursion limit is 1000, and risks overflow on a JVM thread with a default stack.
The loop and its invariant
def reverse(head):
prev, cur = None, head
while cur:
nxt = cur.next # save before overwriting
cur.next = prev # flip the link
prev = cur # grow the reversed prefix
cur = nxt # advance into the untouched suffix
return prevBefore each iteration, prev is the head of the already-reversed prefix, which ends in None. cur is the head of the original, untouched suffix. Those two pieces together hold every node exactly once. The line that saves nxt has to come first. Without it, the flip discards the only reference to the rest of the list.
Trace on 1 -> 2 -> 3:
| step | nxt | cur.next set | prev after | cur after |
|---|---|---|---|---|
| start | None | 1 | ||
| 1 | 2 | 1.next = None | 1 | 2 |
| 2 | 3 | 2.next = 1 | 2 | 3 |
| 3 | None | 3.next = 2 | 3 | None |
The loop exits with cur = None, and the answer is prev, which is 3. Returning cur gives None, which is the most common bug here.
The recursive version
def reverse_rec(head):
if not head or not head.next:
return head
new_head = reverse_rec(head.next)
head.next.next = head
head.next = None # without this, the old head still points forward: a cycle
return new_headTime is O(n) and the call depth is n, so the extra space is O(n) for the stack. Each frame also holds head and new_head. Python has no tail-call elimination, so rewriting the recursion as a tail call doesn't save you.
Failure modes to name
- Missing
head.next = Nonein the recursive version leaves a cycle. The symptom is a hang when the list is printed. - Losing
nxtin the loop truncates the list silently. A test with one node passes, and a test with three nodes fails. - Input of length 0 or 1 must return the input unchanged. Both versions handle it, but only if the empty check comes first.
When I'd use recursion
For short lists, or for a reverse-in-groups variant where the recursion makes the group boundaries easy to state. For anything whose length the caller doesn't control, I'd use the loop, or an explicit stack if the recursive shape is required.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-22In Floyd's cycle detection, once the slow and fast pointers meet inside the cycle, what do you do next to find the node where the cycle begins?
The 60-second answer
Reset one pointer to the head, leave the other at the meeting point, then advance both by one node per step. The node where they next coincide is the entry of the cycle. Cost is O(n) time and O(1) extra space.
Why it works. Let a be the distance from the head to the entry, b the distance from the entry to the meeting point, and L the cycle length. When slow has moved a + b steps, fast has moved 2(a + b). Fast is ahead of slow by a whole number of laps, so 2(a + b) - (a + b) = a + b = kL for some k >= 1. Rearranged, a = kL - b. Walking a steps from the meeting point therefore lands exactly on the entry, because going the remaining b steps round the cycle and then kL - b more is kL, a full set of laps. Starting the second pointer at the head covers the same a steps from the other side.
Trace. List 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 3, so a = 2 (entry is node 3), L = 4. Slow and fast meet at node 5 after slow has moved 4 steps and fast 8. Here b = 2 and a + b = 4 = L, so k = 1. Reset one pointer to node 1. Step both: after one step the head pointer is at node 2 and the meeting pointer is at node 6. After two steps the head pointer is at node 3 and the meeting pointer is also at node 3. Return node 3.
Detection first. The fast pointer moves two nodes per step, the slow one moves one. If the list ends (fast or fast.next is null), there is no cycle. Otherwise the gap closes by one node per step and they must meet within L steps once slow enters the cycle, so detection is guaranteed.
Alternatives and when not to use them. A hash set of visited nodes finds the entry on the first repeat in O(n) time and O(n) space. It is simpler and fine for a small list, but it spends memory the problem may not allow. Floyd's wins when memory is constrained or nodes cannot be hashed by identity.
Failure modes. Checking only fast.next without first checking fast throws a null dereference on even-length lists with no cycle. Resetting both pointers to the head instead of one finds the meeting node again, not the entry. Comparing node values rather than node references fails when values repeat; compare identity.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-23Your k=4,000 sorted sources each stream from a paged reader with a 64 KB buffer, and the merged output must be stable by source order on ties. Which merge do you build, what is its peak memory, and where does a heap of heads break its O(N log k) bound?
The 90-second answer
Use a min-heap of heads, keyed by (value, source_index). The source index makes the output stable: on equal values, the earlier source wins. Each source keeps one head in the heap and one 64 KB page in its buffer. The heap gives O(N log k) time, but with streamed sources the memory and I/O cost is what decides the design, not the comparison count.
Peak memory with all sources resident: 4,000 × 65,536 B = 262,144,000 B, about 250 MiB, plus 4,000 heap entries of a few dozen bytes each, which is negligible. If the budget is 64 MiB, the heap cannot hold a page per source. You need to page sources in and out, and that is where the bound breaks.
Tie trace. Sources A=[2,5], B=[2,3], C=[1,2] (indices 0,1,2):
| Step | Heap (value, src) | Pop | Output |
|---|---|---|---|
| 0 | (1,2),(2,0),(2,1) | ||
| 1 | (2,0),(2,1),(2,2)… | (1,2) | 1 |
| 2 | (2,1),(2,2),(5,0) | (2,0) | 2 |
| 3 | (2,2),(3,1),(5,0) | (2,1) | 2 |
| 4 | (3,1),(5,0),… | (2,2) | 2 |
Without the index, the heap can emit the three 2s in any order, and the output is not stable. Drop the index and nothing crashes; a diff test just becomes flaky.
Where the heap breaks. After popping from source s, you must read s's next element. If its page is exhausted, the refill is a blocking read inside the pop loop. Heap operations stay O(log k), but p99 latency now includes disk seeks, and a single pop can stall for a full read. A prefetch thread per source, or a double buffer, fixes the latency but doubles the 250 MiB peak.
Divide and conquer under the same constraints. Pairwise merging with ceil(log2 4000) = 12 rounds keeps only two input streams open per merge. Per round it writes every record once, so with N total records the I/O is about 12N writes plus 12N reads, against N reads for the heap. If intermediates stay in memory, the peak is about two pages per merge in flight, far below 250 MiB, but then the whole output of each round must fit or spill.
Pick the heap when the budget covers one page per source and you want first output early. Pick D&C when the budget is below k pages and you can afford sequential spill I/O. Stability holds for D&C only if each merge takes from the left run on ties and pairs are adjacent in source order.
Failure modes to name. A read error in the middle of a refill leaves a stale head in the heap. Surface the error and stop, do not emit a partial result as complete. Also, if one source is slow, the heap blocks on it even when others have data ready, so a merged stream can be paced by its slowest source.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-24A service receives an unbounded stream of integers and must report the kth largest value seen so far after each arrival. Compare a bounded min-heap of size k with quickselect over a buffer of everything seen. What does each cost per query, and what is quickselect's worst case?
The 90-second answer
First I'd ask whether queries interleave with arrivals or happen once at the end, and whether k is small compared with n. Assuming queries interleave and n is unbounded, I'd use a min-heap of size k. It holds the k largest values seen so far, and its root is the kth largest. Quickselect needs the whole history, and re-running it per query is O(n) each time, so it only wins for a single offline query where memory for n values is acceptable.
Heap mechanics: while the heap holds fewer than k items, push. After that, a new value x replaces the root only if x is greater than the root (heapreplace), otherwise it is dropped. Each arrival costs O(log k), a query is O(1), and space is O(k).
Trace with k = 3 on the stream 5, 1, 9, 7, 3, 8:
| arrival | action | heap (min at root) | 3rd largest |
|---|---|---|---|
| 5 | push | [5] | n/a |
| 1 | push | [1, 5] | n/a |
| 9 | push | [1, 5, 9] | 1 |
| 7 | 7 > 1, replace root | [5, 7, 9] | 5 |
| 3 | 3 <= 5, drop | [5, 7, 9] | 5 |
| 8 | 8 > 5, replace root | [7, 8, 9] | 7 |
The final answer 7 matches the sorted descending order 9, 8, 7, 5, 3, 1.
Quickselect (partition around a pivot, recurse into the side that contains rank k) has expected O(n) time for one query with a random pivot, since each partition roughly halves the active range. Over a buffer of n = 10^6 int32 values that is about 4 MB and a few million comparisons, once. Re-running it after every arrival is roughly n^2 / 2 total work, which is 5 x 10^11 comparisons at n = 10^6. That rules it out.
Worst case: with a deterministic pivot, such as the first or last element, a sorted or reverse-sorted input removes one element per partition, so one query costs n(n-1)/2 comparisons. Randomised pivots make that input pattern very unlikely but do not remove it. Median-of-medians gives a true O(n) worst case, with a constant large enough that people rarely ship it. The practical fix is introselect: std::nth_element in libstdc++ tracks recursion depth and switches to heap-based selection once depth exceeds about 2 log2 n, bounding the worst case at O(n log n).
Failure modes to name:
- k close to n: the heap holds almost everything, so it costs O(n log n) time and O(n) memory with no advantage. Sorting or quickselect is the better fit there.
- Duplicates: the strict
>test keeps the heap correct, but quickselect partitions with many equal keys need a three-way partition, or it degrades toward quadratic behaviour. - Detection: count comparisons per query in a test harness, and alert on p99 query latency growing with stream length, which is the signature of an O(n) query path hiding in a hot loop.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-25Your service must return a binary tree's values one level at a time, streaming each level out before the next is read. Walk me through the queue-based traversal, then state how much memory it holds at peak and what that depends on.
The 90-second answer
Use breadth-first search with a FIFO queue. Each pass through the outer loop handles exactly one level: record the queue length at the start of the pass, pop that many nodes, and push their children. Whatever is in the queue at the start of a pass is the complete next level, so the level boundary needs no sentinel values or depth tags.
from collections import deque
def levels(root):
if root is None:
return []
out, q = [], deque([root])
while q:
size = len(q)
level = []
for _ in range(size):
node = q.popleft()
level.append(node.val)
if node.left:
q.append(node.left)
if node.right:
q.append(node.right)
out.append(level)
return outTrace on [3, 9, 20, null, null, 15, 7]. Start: q=[3]. Pass 1, size 1: emit [3], push 9, 20. Pass 2, size 2: emit [9, 20], push 15, 7. Pass 3, size 2: emit [15, 7], nothing pushed. Queue empty, done. Three levels, each node enqueued and dequeued once, so time is O(n).
Memory bound
The queue never holds more than one level's worth of nodes plus the children being added for the next one. Peak queue size is therefore the widest level, W, not the height. For a complete tree with n = 10^6 nodes the last level has about n/2 = 500,000 nodes, so the queue peaks near 500,000 references. At 8 bytes per pointer in CPython's deque that is roughly 4 MB of queue on top of the 10^6 node objects, which exist anyway. For a skewed tree (a chain) W is 1, and the queue stays tiny even though the height is 10^6.
Note what this bound does and does not buy. If you return all levels as a list of lists, output is O(n) regardless, so the queue bound only matters when you stream: emit each level and drop it, and peak working memory becomes O(W) instead of O(n).
Alternative: DFS with depth index
Recursive DFS passing depth, appending to out[depth], uses O(h) call stack, where h is height. On a chain of 10^6 nodes that is a stack depth of 10^6 and will hit Python's recursion limit or overflow a native stack. It also cannot stream a level until the traversal finishes, because a later subtree can add to an earlier depth. Pick DFS when the tree is shallow and you want the output built in one recursion. Pick BFS when you need levels in order, want to stream them, or the height may be large.
Failure modes
list.pop(0)as the queue: each pop shifts the array, so the traversal becomes O(n^2) on large levels. Usecollections.dequeor an index into a list.- Forgetting that the size snapshot must be taken before the inner loop. Reading
len(q)inside the loop counts children you just pushed and merges two levels. - Null children pushed onto the queue. The check adds one branch per node; without it, the queue fills with None and the size counts become wrong.
Detection is simple: a test with a chain, a complete tree, and a single node catches all three.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-26Which property of a binary search tree lets you find the lowest common ancestor of two keys without searching the whole tree?
The 60-second answer
The property is the BST ordering invariant: every key in a node's left subtree is less than the node's key, and every key in its right subtree is greater. Because of that, one comparison at a node tells me which subtree both keys are in. If both p and q are smaller than the node, the LCA is in the left subtree. If both are larger, it is in the right subtree. The first node where the keys split, or where one of them equals the node, is the LCA. I only follow one path from the root, so the cost is the tree height, O(h), not O(n).
A plain binary tree has no such ordering. A node's key says nothing about where p and q sit, so I have to search both subtrees. The standard fix is a post-order recursion that returns the node once it finds p or q, and combines the results from the left and right. That is O(n) time and O(h) stack. Parent pointers are another option: walk both nodes up to the root and find where the two paths first meet. That is O(h) too, but it needs the extra pointers.
def lca_bst(root, p, q):
node = root
while node:
if p < node.key and q < node.key:
node = node.left
elif p > node.key and q > node.key:
node = node.right
else:
return nodeTrace. Tree: 6 with left child 2 (children 0 and 4; 4 has children 3 and 5) and right child 8. lca_bst(root, 3, 5): at 6 both keys are below, so go left. At 2 both are above, so go right. At 4, 3 is below and 5 is above, so the keys split here. Return 4. Three comparisons on a seven-node tree.
Failure modes
- Duplicate keys. The split test assumes a strict order. If equal keys can sit in either subtree, a key equal to the node can take the wrong branch. Fix one convention, such as equal keys always go left, and apply it at insert and at query time.
- A missing key. If
porqis not in the tree, the function still returns a node. Check that both keys exist first if the caller needs a guaranteed answer. - A skewed tree. On a degenerate BST the path length is n, so O(h) becomes O(n). Balanced trees give O(log n).
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-27You get a preorder array of int32 values that encodes a binary search tree in which duplicates belong in the right subtree. Validate it in O(n) time without building nodes. What lower-bound sentinel do you use, and what breaks if the array contains INT_MIN?
The 90-second answer
Duplicates going right means the rule is: a value v in the subtree of ancestor u must satisfy v < u if it is in u's left subtree and v >= u if it is in u's right subtree. So lo is inclusive, and the sentinel has to sit strictly below every legal key. A preorder scan with an explicit stack does this in one pass. Each stack entry is an ancestor we have gone left from, and it stays on the stack until a value arrives that belongs in its right subtree.
def valid_preorder_bst(vals):
lo = -(1 << 31) - 1 # int64 sentinel, below every int32 key
stack = []
for v in vals:
while stack and v >= stack[-1]:
lo = stack.pop() # v belongs in this node's right subtree
if v < lo:
return False
stack.append(v)
return TrueThe while pops only while v >= top. The popped value becomes the new lower bound, since everything after it inside that right subtree must be at least that large. The check v < lo is inclusive on the lower side, so a duplicate equal to lo passes.
Trace. Tree: root 5, left child 3, right child 5, whose right child is 7. Preorder: [5, 3, 5, 7].
v=5: stack empty,lostays at the sentinel. Push 5.v=3:3 >= 5is false. Check3 < lopasses. Push 3. Stack[5, 3].v=5: pop 3 (lo=3), then pop 5 (lo=5). Check5 < 5is false, so it passes. Push 5.v=7: pop 5 (lo=5). Check passes. Push 7. Accept.
The overflow trap. Suppose the sentinel is an int32 INT_MIN and the check is written strictly, as if v <= lo: return False. The root INT_MIN then fails immediately, although it is a legal key. Worse, [INT_MIN, INT_MIN] (a root with a duplicate right child) is rejected for the same reason. Two fixes work: an int64 sentinel with the inclusive check above, or an int32 sentinel with the inclusive check. Using lo - 1 or hi + 1 as int32 is the trap that silently wraps.
Where it gets subtle. If duplicates were allowed on the left instead, the pop condition becomes v > top and the check becomes v <= lo. Mixing the two conventions, for example popping on >= but checking <=, passes most small tests and fails on runs of equal keys.
Failure modes and detection.
- Strict check on an inclusive bound: rejects valid right-duplicates. Detect with a property test that generates runs of equal keys and compares against a recursive validator.
- Sentinel at the int32 boundary: detect with inputs containing
INT_MINandINT_MAXin several positions. - Forgetting to pop before checking: accepts a deep violation. Detect with the case
[5, 3, 7, 4], where 4 sits in the left subtree of 5 but is greater than 3's ancestor bound.
Complexity. Each value is pushed and popped at most once, so the time is O(n). The stack holds at most the current left-path length, which is O(h), and O(n) in the worst case for a skewed tree.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-28Serialize a binary tree to a string and deserialize it back using preorder with null markers. Explain how the recursion depth behaves on a skewed tree of 100,000 nodes, and how you would fix it.
The 90-second answer
Write a preorder walk and emit # for every null child. The tree 1(2, 3) becomes 1,2,#,#,3,#,#: 3 real nodes, 4 nulls, 2n+1 tokens in total. Serialization is O(n) time and O(n) output. Deserialization reads the tokens in the same order: the current token is the node, and the following tokens are its left subtree, then its right subtree. No lengths or separators between subtrees are needed, because the markers close each branch.
Space is O(h) for the recursion, where h is the height, not O(n) as people often assume. That is where a skewed tree hurts. A right-leaning chain of 100,000 nodes has h = 100,000.
class Node:
def __init__(self, val, left=None, right=None):
self.val, self.left, self.right = val, left, right
def serialize(root):
out, stack = [], [root]
while stack:
n = stack.pop()
if n is None:
out.append('#')
continue
out.append(str(n.val))
stack.append(n.right) # pushed first so left pops first
stack.append(n.left)
return ','.join(out)
def deserialize(s):
tok = s.split(',')
if tok[0] == '#':
return None
root = Node(int(tok[0]))
stack = [[root, 0]] # [node, next slot: 0=left, 1=right, 2=done]
i = 1
while stack:
top = stack[-1]
if top[1] == 2:
stack.pop()
continue
slot = top[1]
top[1] += 1
if i >= len(tok):
raise ValueError('truncated input')
t = tok[i]; i += 1
if t == '#':
continue
child = Node(int(t))
if slot == 0:
top[0].left = child
else:
top[0].right = child
stack.append([child, 0])
return rootTrace for 1,2,#,#,3,#,#: node 1 takes slot 0 and reads 2, so 2 is pushed. Node 2 reads # and # and pops. Node 1 then takes slot 1 and reads 3. Node 3 reads two nulls and pops, and node 1 pops.
The recursive version and the limit. The recursive form of the same logic recurses once per level, so a 100,000-deep chain needs 100,000 frames. CPython's default recursion limit is 1000, so it raises RecursionError near depth 1000. Calling sys.setrecursionlimit does not make this safe. The limit counts Python frames, but the C stack underneath is fixed in size, and a high enough limit can crash the process with a segfault instead of an exception. The explicit stack above moves the depth onto the heap, so memory use is proportional to h but no call-stack limit applies. In a language like Java, the same problem appears as StackOverflowError at the default thread stack size.
Trade-offs and failure modes.
- Preorder with
#needs no lengths, which makes it compact. Level order needs more markers for the same tree. - The
#marker collides with values that are strings containing#or commas. For arbitrary values, length-prefix each token or escape them. - Truncated input shows up as an index error in a naive version. The guard above turns it into an explicit error.
How to test it. Round-trip random trees and check serialize(deserialize(s)) == s. Add a path graph of 100,000 nodes to the suite. A RecursionError or a crash there means the recursive version slipped in.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-29Walk me through solving 0/1 knapsack with a 2-D DP table indexed by item and capacity, then explain why the 1-D rewrite must iterate capacity in reverse and what breaks if it runs forward.
The 90-second answer
Define dp[i][c] as the best total value using only the first i items with capacity c. Each item has two choices: skip it, giving dp[i-1][c], or take it when it fits, giving dp[i-1][c-w] + v. The answer is dp[n][W]. Time is O(nW) and the table takes O(nW) memory. Because each row reads only the row above, one array of length W+1 is enough, but only if capacity is scanned from high to low.
2-D table. Items A(w=2, v=3), B(w=3, v=4), C(w=4, v=5), capacity W=5.
| i \ c | 0 | 1 | 2 | 3 | 4 | 5 |
|---|---|---|---|---|---|---|
| 0 (none) | 0 | 0 | 0 | 0 | 0 | 0 |
| 1 (A) | 0 | 0 | 3 | 3 | 3 | 3 |
| 2 (B) | 0 | 0 | 3 | 4 | 4 | 7 |
| 3 (C) | 0 | 0 | 3 | 4 | 5 | 7 |
Cell dp[2][5]=7 is B plus dp[1][2]=3, so A and B together, weight 5. Read the answer from the bottom right.
def knapsack_2d(items, W):
n = len(items)
dp = [[0] * (W + 1) for _ in range(n + 1)]
for i, (w, v) in enumerate(items, 1):
for c in range(W + 1):
dp[i][c] = dp[i-1][c]
if c >= w:
dp[i][c] = max(dp[i][c], dp[i-1][c-w] + v)
return dp[n][W]Collapsing to one row. Keep one array dp[c], initially zero. For each item, the update dp[c] = max(dp[c], dp[c-w] + v) must read the old row dp[i-1]. Reading dp[c-w] works only if it has not yet been overwritten for this item. Going from high c to low c guarantees that, since c-w < c is still untouched when you reach c.
Trace with the reverse loop: after A, dp=[0,0,3,3,3,3]. For B, c=5 gives max(3, dp[2]+4=7)=7, c=4 gives max(3, dp[1]+4)=4, c=3 gives max(3, dp[0]+4)=4, so dp=[0,0,3,4,4,7]. For C, c=5 gives max(7, dp[1]+5)=7 and c=4 gives max(4, dp[0]+5)=5, so the final array is [0,0,3,4,5,7], and dp[5]=7 matches the table.
Forward order for item A breaks it. c=2 writes 3, c=3 writes 3, then c=4 reads dp[2], which already holds A's value 3, and writes 6. That is A taken twice, weight 4 and value 6, which is impossible. The 2-D version never has this problem because it reads row i-1, which is never written during row i.
Failure modes. Iterating c from W down to w (not to 0) is the usual off-by-one: stopping at 0 is harmless but wasteful, and reading c-w when c<w gives a negative index that Python silently wraps. Unbounded knapsack reverses the logic: scan forward so that using the same item again is allowed.
When not to use it. If capacity is 10^9 but item count is small, O(nW) is infeasible. Use branch and bound, meet in the middle (O(2^(n/2))), or scale values if they are integers and bounded.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-30For a sparse social graph with V users and E friendships, how much space does an adjacency matrix need compared with an adjacency list?
The 30-second answer
An adjacency matrix needs V² cells, whatever the number of friendships. An adjacency list needs O(V + E) entries. When E is much smaller than V², which is what sparse means, the list is the representation to use, and the gap grows with V.
Why. The matrix stores a slot for every ordered pair of users, so it pays for pairs that are not friends. The list stores one entry per vertex plus one per edge end. Friendship is undirected, so each friendship appears twice, giving about V + 2E entries, which is still O(V + E).
| Representation | Space | Check a single pair (u, v) | List all friends of u |
|---|---|---|---|
| Adjacency matrix | O(V²) | O(1) | O(V), scans a full row |
| Adjacency list | O(V + E) | O(deg(u)), or O(log deg(u)) if sorted | O(deg(u)) |
Worked check. Take V = 10⁶ users with an average of 100 friends each. That gives E = 5 × 10⁷. The matrix needs 10¹² cells, about 125 GB as one bit per cell. The list needs about 10⁶ + 10⁸ entries, roughly 400 MB at 4 bytes per id. These are hypothetical figures, labelled as such.
When the answer changes. A dense graph, where E approaches V², can justify a matrix, because the O(V²) space is then close to the list's size and the O(1) pair check pays off. If the relation is directed, the list stores E out-edges, not 2E, and you add an in-edge index if you need followers.
Failure mode to name. Per-vertex objects with pointers, rather than a packed array of ids, can use several times the raw space because of allocator overhead and cache misses. Measure bytes per edge on a sample shard to catch it.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-31Your build graph has 40,000 targets and 200,000 dependency edges. Kahn's algorithm stops with 312 targets never emitted. How do you report the cycle members to the user, and what does the whole run cost in big-O terms?
The 60-second answer
Kahn's algorithm works on in-degrees. Compute the in-degree of every target, push every zero-in-degree target onto a queue, then repeatedly pop a target, emit it, and decrement the in-degree of each dependant. If a dependant reaches zero, enqueue it. When the queue empties, the emitted count tells you everything: if it equals V, the emitted sequence is a valid build order; if it is less, the graph has a cycle, and the 312 unemitted targets are exactly the nodes that lie on a cycle or are downstream of one.
That last point matters for the report. Unemitted does not mean cyclic. A target that depends on a cycle never reaches in-degree zero, so it is stuck too. Reporting all 312 as "in the cycle" is wrong and sends engineers chasing the wrong targets.
Isolating the members. Take the residual subgraph (the unemitted nodes and the edges among them). Every node there has in-degree at least 1 from another residual node, so walking backwards along residual edges from any node must eventually revisit a node. That revisit closes a cycle. Run one such walk, record the path, and report it as the minimal witness. To list every strongly connected cycle, run Tarjan's SCC on the residual subgraph: any SCC with more than one node, or a self-loop, is a cycle group. Tarjan is O(V + E) on the residual, so it does not change the bound.
Trace on a small case. Targets A, B, C, D with edges A→B, B→C, C→B, D→C. In-degrees: A 0, B 2, C 2, D 0. Queue starts with [A, D]. Pop A, B drops to 1. Pop D, C drops to 1. Queue empty, emitted 2 of 4. Residual: {B, C}, with B→C and C→B. Walking back from B: B ← C ← B, so the cycle is B, C. Note that D was emitted correctly; the fault is in the B/C pair, not in D's chain.
Cost. Computing in-degrees touches every edge once: O(E). Each target is enqueued and dequeued once, and each edge is decremented once when its source is emitted: O(V + E) total. Cycle reporting by Tarjan on the residual is also O(V' + E') with V' ≤ V and E' ≤ E, so the whole thing stays O(V + E). For 40,000 targets and 200,000 edges that is roughly 240,000 basic operations, well under a millisecond of work; the cost that matters in practice is reading the graph, not the sort.
Failure modes.
- Duplicate edges inflate in-degree. If the manifest lists A→B twice, the decrement happens twice too, so it balances. Problems appear only if you dedupe on one side and not the other. Dedupe once, at graph construction.
- Self-dependencies (a target listing itself) show up as a residual node with a self-loop. Check for them explicitly, because the backward walk will find them immediately but users often miss them.
- Non-deterministic order: the queue order depends on insertion order. If the build must be reproducible, sort the zero-in-degree set by target name before seeding, or use a priority queue keyed by name.
State the assumption up front: the graph is a static snapshot, and the report must name cycles rather than just fail.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-32Your service consumes a stream of 10^8 'these two accounts are the same person' pairs and must answer same-group queries in near-constant time. Explain union-find with path compression and union by rank, what bound it achieves, and where it fits.
The 90-second answer
Keep a parent array and a rank per node. rank is an upper bound on tree height, and only roots' ranks matter. find walks to the root and points every node on the path straight at it. union attaches the root of the shorter tree under the taller one, and increments rank only when the two ranks are equal. With both optimizations, m operations on n elements cost O(m · α(n)) in total, where α is the inverse Ackermann function. For any n that fits in memory, α(n) ≤ 4, so I treat each operation as constant. The bound is not O(1) in the strict sense, and I would say that explicitly.
Trace. Six nodes, all ranks 0, parent = [0,1,2,3,4,5].
| Step | Operation | Result | parent |
|---|---|---|---|
| 1 | union(0,1) | equal rank 0, attach 1 under 0, rank[0]=1 | [0,0,2,3,4,5] |
| 2 | union(2,3) | attach 3 under 2, rank[2]=1 | [0,0,2,2,4,5] |
| 3 | union(1,3) | roots 0 and 2, both rank 1, attach 2 under 0, rank[0]=2 | [0,0,0,2,4,5] |
| 4 | find(3) | path 3→2→0, compresses to 3→0 | [0,0,0,0,4,5] |
Step 4 is where compression pays: the next find(3) costs one hop.
# Python 3.11
def find(x):
while parent[x] != x:
parent[x] = parent[parent[x]] # path halving: one pass, same bound
x = parent[x]
return x
def union(a, b):
ra, rb = find(a), find(b)
if ra == rb:
return False # already connected: this is a cycle in an undirected graph
if rank[ra] < rank[rb]:
ra, rb = rb, ra
parent[rb] = ra
if rank[ra] == rank[rb]:
rank[ra] += 1
return TruePath halving avoids the recursion-depth problem of full recursive compression. A recursive find on a chain of 10^6 nodes can exhaust the default stack, so I use the iterative form.
Why both optimizations. Union by rank alone gives O(log n) per find, because height grows only when two equal trees merge. Path compression alone gives O(log n) amortized per operation on adversarial union orders. Together, Tarjan's analysis gives the inverse Ackermann bound, which is tight for this structure.
Failure modes I watch for.
- Union without rank or size: a sequence of unions can build a chain, and every
findafter it walks linearly. - Calling
unionon raw ids withoutfind: you link a non-root and silently split a component. - Forgetting the
ra == rbreturn: you miss the cycle signal that Kruskal and cycle detection depend on. - Using rank as if it were height after compression: compression lowers real heights, so rank is only an upper bound.
Where it fits. Kruskal's MST, where the sort dominates and union-find is nearly free. Connected components while edges arrive. Offline dynamic connectivity and percolation experiments. Image labelling in two passes.
Where it does not. Anything that deletes edges or nodes, since the structure cannot split a set. Path queries or the actual route between two nodes, which need a spanning forest with extra data or link-cut trees. Connectivity that must be answered with an explanation of the path rather than a yes or no.
For your stream: each pair is one union, each query is two finds, and memory is two integer arrays of size n. Account identifiers need an interning map to dense indices first.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-33A connected undirected graph has V = 1,000 vertices and is nearly complete, stored as a 1,000 by 1,000 weight matrix. Compare Kruskal and Prim for its minimum spanning tree. Which do you pick, and what does that choice cost?
The short answer
For a dense graph held as a matrix, I use Prim with a linear scan for the minimum key. It runs in O(V^2), and that matches the cost of reading the matrix. Kruskal is O(E log E), and on a dense graph E is close to V^2, so the sort dominates and the log factor is paid for nothing.
Why the costs differ
Kruskal sorts all edges by weight, then adds each edge that joins two different components, using union-find. Its cost is O(E log E) for the sort plus nearly constant time per union-find operation. Getting the edges out of the matrix is itself an O(V^2) scan, so Kruskal never beats the input size.
Prim grows one tree from a start vertex. Each step picks the non-tree vertex with the smallest key, then relaxes its neighbours. With a matrix, the neighbours are one row, read sequentially. Picking the minimum is a linear scan of V keys. Total work is V iterations of O(V) scan plus O(V) relaxation, so O(V^2).
With real figures: V = 1,000 gives about 500,000 undirected edges. Prim does roughly 10^6 key reads and writes in cache-friendly row order. Kruskal sorts 500,000 edges, about 500,000 times log2(500,000), which is around 9.5 million comparisons, with the sort moving edge records around in memory. Both finish in milliseconds, but Prim does less work and touches memory more predictably.
Prim with a heap is the wrong choice here
A binary heap with lazy deletion gives O(E log V), which for E near V^2 is O(V^2 log V). That is worse than the linear scan. An indexed heap with decrease-key has the same asymptotic cost. Fibonacci heaps give O(E + V log V) in theory, but the constant factors and pointer chasing rarely win at V = 1,000.
When Kruskal wins
Sparse graphs, where E is about V, make the sort cheap, and Kruskal is simpler and often faster. It also wins when the edges already arrive as a list, or when you need edges in weight order for other reasons, such as clustering by cutting the last k-1 MST edges.
Failure modes to check
If the graph is disconnected, Prim started from one vertex reaches fewer than V vertices and Kruskal ends with fewer than V-1 edges. Either way, detect it by counting: a spanning tree has exactly V-1 edges. Negative weights are fine for MST, unlike shortest paths, because the cut property still holds. Ties are safe for both algorithms, but tie-breaking changes which MST you get, not its total weight, so do not compare edge sets across implementations as if they must match.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-34In sliding window maximum with a monotonic deque, why does the whole pass cost O(n) instead of O(n·k) for window size k?
The 60-second answer
The deque holds indices whose values are strictly decreasing from front to back, so the front is always the index of the current window's maximum. Each index is appended exactly once, when it arrives. It leaves the deque at most once: either from the back, because a later and larger-or-equal value made it irrelevant, or from the front, because it slid out of the window. So across n elements there are at most n appends and at most n pops. The work is O(n) total, which is O(1) amortized per element. The window size k never multiplies the work, because the inner loops only remove elements; they never rescan the window.
Code (Python 3.12)
from collections import deque
def max_sliding(nums: list[int], k: int) -> list[int]:
dq = deque() # indices, values decreasing front to back
out = []
for i, x in enumerate(nums):
while dq and dq[0] <= i - k: # front index left the window
dq.popleft()
while dq and nums[dq[-1]] <= x: # back values can never be a max again
dq.pop()
dq.append(i)
if i >= k - 1:
out.append(nums[dq[0]])
return outTrace
nums = [1, 3, -1, -3, 5, 3, 6, 7], k = 3.
| i | x | deque after the step (indices) | window output |
|---|---|---|---|
| 0 | 1 | [0] | none yet |
| 1 | 3 | [1] (0 popped, 1 <= 3) | none yet |
| 2 | -1 | [1, 2] | 3 |
| 3 | -3 | [1, 2, 3] | 3 |
| 4 | 5 | [4] (1 and 2 and 3 popped) | 5 |
| 5 | 3 | [4, 5] | 5 |
| 6 | 6 | [6] (4 and 5 popped) | 6 |
| 7 | 7 | [7] | 7 |
At i = 4, index 1 is removed from the front because 1 <= 4 - 3. Then the back pops remove indices 3 and 2, since their values are not larger than 5. Output: [3, 3, 5, 5, 6, 7].
Why each index is pushed and popped once
An index enters once, on its own iteration, and it has exactly two ways out. The back-pop loop removes it when a newer value is at least as large, so it can never be the maximum of any later window. The front-pop loop removes it when its position falls outside the window. Once gone, an index is never re-inserted. Those two facts give the bound: total pops cannot exceed total pushes, and total pushes equal n.
Failure modes and what to check
- Using
<instead of<=in the back-pop loop keeps duplicate maxima. That still returns correct answers, but the deque grows larger, and equal values are never dropped early. - Forgetting the front-expiry check is the usual bug. The output then reports a maximum from outside the window. A brute-force comparison on small random inputs catches it immediately.
- Storing values instead of indices makes expiry impossible to check, because two equal values at different positions cannot be told apart.
- k greater than len(nums) should be rejected or handled explicitly. The code above returns an empty list in that case.
When not to use it
If the window is not sliding (arbitrary range queries over a static array), a sparse table answers each query in O(1) after O(n log n) preprocessing. For a streaming max over a window that only grows, a single running maximum is enough.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-35A service holds 10^6 counters incremented by up to 10^9 per point update, while range queries ask for sums over recent activity. A daily snapshot must not block readers. Prefix sums, a Fenwick tree or a segment tree: which do you pick, what does one update cost in each, and where does your choice break under the snapshot requirement?
The 90-second answer
I would not pick any of them unchanged. The constraints interact: the sums are invertible and updates are point adds, but the snapshot must not block readers, so the structure must support a consistent read while writes continue. That points to a Fenwick tree with a double-buffered snapshot, not prefix sums.
- Prefix sums fail on the update path. One point add of 10^9 at index i rewrites P[i..n], up to 10^6 writes. A snapshot is cheap (copy the array), but every update during a snapshot window is O(n) under the lock.
- Fenwick tree gives O(log n) point add and O(log n) prefix query, about 20 node touches at n = 10^6. Memory is 10^6 + 1 signed 64-bit integers, about 8 MB. Sums reach 10^6 times 10^9 = 10^15, so 64-bit is required, and 32-bit overflow is silent.
- Segment tree gives the same O(log n) but roughly 2 to 4 times the memory and a larger constant. It only wins if the snapshot needs per-node versioning with range assigns, which this workload does not require.
Trace of the update path. Array a = [3,1,4,1,5,9], 1-indexed. Node i covers (i - lowbit(i), i]. Add 2 at index 3: node 3 goes 4 to 6, node 4 goes 9 to 11, node 8 is out of range and the loop stops. Two touches for n = 6, about log2(n) in general.
Snapshot under load. Copy the Fenwick array under a short write lock (about 8 MB memcpy, under a millisecond on modern hardware) and serve the snapshot to readers. Updates after the copy go to the live array. Reading the live array without a lock risks torn 64-bit reads on 32-bit platforms and mid-update prefix sums, so the reader must use the snapshot or a lock.
Subtle failure mode. Fenwick range queries compute prefix(r) minus prefix(l-1). If a daily reset zeros the array in place while a reader holds the old prefix(r) and reads the new prefix(l-1), the difference is garbage and no exception is raised. Detect it with a generation counter on the snapshot and reject mismatched reads.
When not to use this. If queries are few and updates are rare, a rebuilt prefix-sum array per snapshot is simpler and O(1) per query. The Fenwick choice is justified by the interleaved updates during the snapshot window, and I would measure the update-to-query ratio before committing.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-36You have n jobs, each with a start and finish time, and one machine that runs one job at a time. Choose the largest set of jobs that don't overlap. Why does sorting by earliest finish work, and why do earliest start or shortest length fail?
The 60-second answer
Treat each job as a half-open interval [s, f), so a job may start the instant the previous one finishes. Sort by finish time, scan once, and keep a job whenever its start is at or after the finish of the last job kept. That gives a maximum-size set. Cost is O(n log n) for the sort and O(n) for the scan.
Finish time is the only thing a chosen job takes away from the future. Among jobs that are compatible right now, the one that ends first leaves the most room for everything after it.
Two tempting alternatives fail, and each needs only three jobs to show it:
| Greedy order | Input | Picks | Count | Optimal |
|---|---|---|---|---|
| earliest start | [0,10], [1,2], [3,4] | [0,10] | 1 | 2 |
| shortest length | [0,4], [3,6], [5,9] | [3,6] | 1 | 2 |
In the second row, [3,6] is shortest but overlaps both other jobs. Earliest finish picks [0,4] and then [5,9].
Trace. Jobs: J1 [1,4], J2 [3,5], J3 [0,6], J4 [5,7], J5 [8,9], J6 [5,9]. Sorted by finish, with last = the finish of the last kept job:
| Job | s, f | s >= last? | Decision | last after |
|---|---|---|---|---|
| J1 | 1, 4 | start of schedule | keep | 4 |
| J2 | 3, 5 | 3 >= 4? no | skip | 4 |
| J3 | 0, 6 | 0 >= 4? no | skip | 4 |
| J4 | 5, 7 | 5 >= 4? yes | keep | 7 |
| J5 | 8, 9 | 8 >= 7? yes | keep | 9 |
| J6 | 5, 9 | 5 >= 9? no | skip | 9 |
Result: J1, J4, J5, count 3.
def max_jobs(jobs):
last = float('-inf')
picked = []
for s, f in sorted(jobs, key=lambda j: j[1]):
if s >= last:
picked.append((s, f))
last = f
return pickedWhy it is optimal (exchange argument). Let greedy pick g1..gk in finish order, and let an optimal schedule be o1..om sorted the same way. Claim: f(g_i) <= f(o_i) for every i where both exist.
Base case: g1 has the smallest finish of any job, so f(g1) <= f(o1).
Step: assume f(g_i) <= f(o_i). Then s(o_(i+1)) >= f(o_i) >= f(g_i), so o_(i+1) is compatible with g_i. The scan reaches o_(i+1) after g_i, and it takes the first compatible job it meets. Jobs arrive in finish order, so the job it takes has finish at most f(o_(i+1)). Hence f(g_(i+1)) <= f(o_(i+1)).
If m > k, then o_(k+1) is compatible with g_k and comes later in the order, so greedy would have taken it. That contradicts how the scan ended, so k = m. Equivalently, you can swap o1 for g1 in any optimal schedule without breaking feasibility, then repeat.
Failure modes.
- Closed intervals where touching counts as overlap: the test becomes s > last.
- Updating last on skipped jobs: last must hold the finish of the last kept job only.
- Ties on finish: any order among them is fine, because the proof only uses finish order.
When not to use it. Weighted jobs break greedy. Sort by finish, compute for each job the last compatible predecessor with binary search, and run DP: best[i] = max(best[i-1], w_i + best[p(i)]). That is O(n log n). With k identical machines, keep a min-heap of machine free times and assign each job to the machine that frees earliest among those ready by s, O(n log k).
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-37Given meeting intervals [start, end) for one day, return the minimum number of rooms needed. Compare a sorted sweep over separate start and end arrays with a min-heap of end times. What does each cost, and what does each one tell you beyond the room count?
Assumptions first. Intervals are half-open, so a meeting ending at 10 frees its room for one starting at 10. Up to 10^6 meetings, integer times. The answer is the peak number of simultaneous meetings.
Sweep over sorted endpoints. Sort the starts and the ends separately. Walk the starts in order, and before taking a room, release every room whose meeting has already ended by that start.
def min_rooms(intervals):
starts = sorted(s for s, _ in intervals)
ends = sorted(e for _, e in intervals)
rooms = best = j = 0
for s in starts:
while ends[j] <= s:
rooms -= 1
j += 1
rooms += 1
best = max(best, rooms)
return bestThe <= is the tie rule. A meeting ending at 10 must release before one starting at 10 claims a room. Using < would report two rooms for back-to-back meetings. The while loop cannot run past the end array, because each admitted meeting has an end strictly greater than its start, so at least one end is always still ahead of the current start.
Min-heap of end times. Sort intervals by start. The heap holds the end time of every room in use. If the earliest-ending room is free by this start, reuse it; otherwise open a new one.
import heapq
def min_rooms_heap(intervals):
heap = []
for s, e in sorted(intervals):
if heap and heap[0] <= s:
heapq.heapreplace(heap, e)
else:
heapq.heappush(heap, e)
return len(heap)Trace on [[0,30],[5,10],[15,20]]. Sweep: starts [0,5,15], ends [10,20,30]. At 0, rooms=1. At 5, 10 <= 5 is false, rooms=2. At 15, 10 <= 15 releases one (rooms=1), 20 <= 15 is false, admit (rooms=2). Answer 2. Heap: after sorting, push 30, then 10 is pushed since 30 > 5, heap [10,30]. At 15 the top 10 is free, so heapreplace with 20 gives [20,30]. Answer 2.
Costs. Both sort, so O(n log n) time dominates. The sweep then does O(n) work over two int arrays, 2n integers of memory, with no pointer chasing. The heap does O(n log r) work, where r is the peak room count, and holds at most r ends. With few rooms the heap is cheap; with many concurrent meetings it approaches the sort cost plus log factors.
What the heap tells you that the sweep does not. It knows which room is freed, so you can return a room id per meeting, which a booking UI needs. The sweep only knows counts. If you need the assignment, the heap is the structure to use; if you only need the number, the sweep avoids the heap entirely.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-38Two sorted integer arrays have lengths m and n, and you need their median without merging them. What is the best time bound, and which array do you binary search over?
The 90-second answer
I'd binary search the partition point over the shorter array, which gives O(log min(m, n)) time and O(1) extra space. Merging is O(m + n), which is wasteful when only the middle matters. The search doesn't need the merged array at all, only the largest element on the left side of each cut and the smallest on the right.
Let the shorter array be A (length m) and the longer be B (length n). Pick a cut i in A, meaning i elements of A go left. The total left side must hold (m + n + 1) / 2 elements, so the cut in B is j = (m + n + 1) / 2 - i. The cut is correct when every left element is at most every right element: A[i-1] <= B[j] and B[j-1] <= A[i]. If A[i-1] > B[j], too many A elements are on the left, so move i left. If B[j-1] > A[i], move i right. Searching over the shorter array keeps the range [0, m] small, and it also keeps j inside [0, n].
def median_two_sorted(A, B):
if len(A) > len(B):
A, B = B, A
m, n = len(A), len(B)
half = (m + n + 1) // 2
lo, hi = 0, m
while lo <= hi:
i = (lo + hi) // 2
j = half - i
a_left = A[i-1] if i > 0 else float('-inf')
a_right = A[i] if i < m else float('inf')
b_left = B[j-1] if j > 0 else float('-inf')
b_right = B[j] if j < n else float('inf')
if a_left <= b_right and b_left <= a_right:
if (m + n) % 2:
return max(a_left, b_left)
return (max(a_left, b_left) + min(a_right, b_right)) / 2
if a_left > b_right:
hi = i - 1
else:
lo = i + 1Trace. A = [1, 3], B = [2, 4, 5, 6]. Total 6, so the left half holds 3 elements. Search i in [0, 2].
| step | lo, hi | i | j | left: A, B | right: A, B | check |
|---|---|---|---|---|---|---|
| 1 | 0, 2 | 1 | 2 | [1], [2, 4] | [3], [5, 6] | b_left=4 > a_right=3, move right |
| 2 | 2, 2 | 2 | 1 | [1, 3], [2] | [], [4, 5, 6] | valid |
Even total, so the median is (max(3, 2) + min(inf, 4)) / 2 = 3.5, which matches the merged sequence 1, 2, 3, 4, 5, 6.
Failure modes to name out loud
- Empty arrays. Sentinels for out-of-range indices (plus or minus infinity) make the empty case fall out of the same check. Without them you get index errors on the first comparison.
- Off-by-one on the partition size. Using
(m + n) // 2for the left size is wrong for odd totals. Use(m + n + 1) // 2so the left side is never smaller than the right. - Searching the longer array. It still terminates and gives the right answer, but it costs O(log max(m, n)) and can index past the shorter array's bounds if you aren't careful.
- Overflow. In fixed-width integers,
(a + b) / 2can overflow. Computea + (b - a) / 2or widen the type when the values are large.
When not to use it. If the arrays arrive as streams, or you need the k-th element for many different k, a heap or a selection routine over the merged data can be simpler. For one median over two in-memory sorted arrays, the partition search is the bound interviewers expect you to name, and the one I'd defend.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-39Design a per-client token bucket rate limiter for an API at 10^7 active clients. What state do you keep per client, how do you compute refill, and how does it differ from a fixed window counter?
The 90-second answer
Each client gets a bucket with a capacity C and a refill rate R tokens per second. Per client I store two fields: tokens and last_ms, the timestamp of the last update. On a request at time now, I add (now - last_ms) * R tokens, cap at C, and admit the request only if at least one token is available. Refill happens lazily, on demand, so no timer runs per client.
Floating point drifts across millions of updates, so I keep integers. For a limit of 100 requests per 60 s, set the scale to the window length in milliseconds, W = 60000. Store scaled = tokens * W. Each elapsed millisecond adds C = 100 scaled units, and each request costs W = 60000. One millisecond of refill is then exactly 1/600 of a token, with no rounding.
A fixed window counter keys on floor(now / 60 s) and counts within that bucket. Its flaw is the boundary. A client sends 100 requests at 59.0 s and 100 more at 61.0 s. Both pass, because they land in different windows. That is 200 requests in 2 s against a stated limit of 100 per minute.
Token bucket on the same trace: at 59.0 s the bucket is full, so 100 requests drain it to zero. At 61.0 s, 2000 ms have refilled 2000 * 100 = 200000 scaled units, which is 3.33 tokens. The client gets 3 requests and the rest get 429. Burst size is bounded by C, and sustained throughput by R.
| Property | Fixed window | Token bucket |
|---|---|---|
| State per client | one counter, one window key | tokens, last_ms |
| Worst burst in 2 s, limit 100/min | 200 | 100 (plus refill) |
| Clock dependence | window alignment | elapsed time only |
| Cost to compute | one increment | one multiply, one min |
Atomicity. Read, refill, decide and write must be one step. With Redis I use a Lua script on one key per client, so there is no read-modify-write race between app nodes. Under contention, two nodes that both read tokens = 1 would otherwise both admit a request.
Clocks. Use one time source for all nodes, such as Redis TIME inside the script. Per-node wall clocks skew by milliseconds, and a node running ahead refills a client's bucket early.
Memory. A bucket is a key plus two integers, roughly 100 bytes with Redis overhead. At 10^7 clients that is about 1 GB. A bucket that has been full for longer than C / R can be evicted, since a fresh bucket is identical.
Failure modes to watch. A single hot client serialises on one Redis key, so p99 rises once that key sees more than a few thousand scripts per second. Monitor script latency p99 and the 429 ratio per tier. If the limiter's Redis is unreachable, decide explicitly whether to fail open or closed for each route.
Retry-After. The wait is the deficit divided by the rate. If the bucket holds 0.4 tokens and needs 1 at 1/600 tokens per ms, return Retry-After of 600 * 0.6 = 360 ms, rounded up to whole seconds per the header's integer format.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-40A parking lot has spots of two sizes, and a new vehicle type arrives that needs a spot with a charger. Which class decides spot allocation, and how do you add the new type without editing existing code?
The 60-second answer
The vehicle states what it needs. The spot states what it offers. The lot asks the index for a spot and does not inspect vehicle types. Allocation lives in one class, SpotIndex. It buckets free spots by (size, features), and for a vehicle it looks at the head of every bucket that fits, then takes the nearest of those heads.
Vehicle only declares min_size and features. A new type is a subclass that sets those two attributes. If it needs a feature no spot has yet, spots carry that tag when they are built, and the index creates the bucket on the first add. No existing class changes.
from heapq import heappush, heappop
from collections import defaultdict
class Vehicle:
min_size = 1
features = frozenset()
class Motorcycle(Vehicle):
min_size = 1
class Car(Vehicle):
min_size = 2
class EVCar(Car): # new type, no other class changes
features = frozenset({'charger'})
class SpotIndex:
def __init__(self):
self._heaps = defaultdict(list) # (size, features) -> min-heap of (distance, spot_id)
def add(self, size, features, distance, spot_id):
heappush(self._heaps[(size, features)], (distance, spot_id))
def take_for(self, v):
best = None # (bucket_key, head) where head = (distance, spot_id)
for key, h in self._heaps.items():
size, feats = key
if h and size >= v.min_size and feats >= v.features:
if best is None or h[0] < best[1]:
best = (key, h[0])
if best is None:
return None
return heappop(self._heaps[best[0]])[1]
class ParkingLot:
def __init__(self, index):
self.index = index
def park(self, v):
return self.index.take_for(v)Trace
Add three spots:
idx = SpotIndex()
idx.add(1, frozenset(), 3, 'A')
idx.add(2, frozenset(), 5, 'B')
idx.add(2, frozenset({'charger'}), 2, 'C')Buckets: (1, {}) holds A at distance 3, (2, {}) holds B at distance 5, (2, {charger}) holds C at distance 2.
A Car has min_size 2 and empty features. The loop visits (1, {}) first, but its size 1 fails size >= 2. (2, {}) passes: head is (5, 'B'), so best is that. (2, {charger}) passes too, since {charger} >= frozenset() holds, and its head (2, 'C') has 2 < 5, so best becomes C. take_for pops from the charger bucket and returns 'C'.
An EVCar then has min_size 2 and features {charger}. The only bucket with a charger is now empty, so take_for returns None. The EV is turned away while B, a plain spot, sits free.
That is the consequence of the subset rule. Choose one of these policies explicitly:
- Reserve charger spots for EVs: change the test to
feats == v.features. A plain car then never sees the charger bucket, and an EV never takes a plain spot. This is the choice I would make for this lot, because a charger is scarce and cars are not the ones who need it. - Let any vehicle use a charger spot when nothing else is free: keep the subset test, but scan plain buckets first and fall back to charger buckets.
Failure modes
- Concurrent gates.
take_forscans and then pops in separate steps with no lock. Two gates can both see the same head and both pop it, or one pops it after the other has already returned it. Hold one lock across the scan and the pop, or pop and then verify the spot is still free. - Scarce features taken by generic vehicles. With the subset rule, a car takes the only charger spot and an EV arrives to a full lot. Count charger spots against EV arrivals per hour to size the reservation, or use the exact-match rule above.
- Bucket growth. The scan is linear in the number of distinct
(size, features)keys. That is harmless with a handful of keys and a measurable cost at dozens, which is when a per-feature index becomes worth the extra code.
When not to use this shape
With a few spot kinds and no plans for new vehicle types, a plain enum and a switch are clearer. The subclass and index split pays off when new vehicle types arrive without a change window.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-41An LRU cache calls a virtual eviction-policy object on every hit. Explain what that virtual call costs compared with the hash lookup it sits beside, and why the policy's update must stay O(1) under the cache lock.
The 90-second answer
The dispatch is cheap. A virtual call is an indirect branch plus a load of the vtable pointer. When the target predicts well it costs about 1 to 3 ns on a modern x86 core. A hash lookup in a cache-resident table costs in the same range, and a miss to DRAM costs about 80 to 100 ns. So one indirect call per hit adds a few percent to the hit path, and the lock and the value copy usually cost more. The vtable is not the risk. The risk is what the policy does inside the critical section.
That is why onHit must be O(1). Under LRU it moves a list node to the head. If the policy has to search for the key, every hit does work proportional to cache size while every other reader waits.
To make that O(1) the policy needs a stable handle to the node, not a key it must look up again. The cache stores the handle next to the value in its map, so one hash lookup yields both, and the policy relinks the node in constant time.
Trace of one hit, with hypothetical figures labelled as such:
| Step | Work | Cost (hypothetical) |
|---|---|---|
| 1 | hash lookup, returns entry with node handle | ~20 ns |
| 2 | take lock | ~20 ns uncontended |
| 3 | copy value, policy.onHit(handle) relinks node | ~5 ns plus one indirect call |
| 4 | release lock | ~10 ns |
If someone instead writes onHit(key) and the policy re-finds the node through its own map, step 3 becomes a second hash lookup inside the lock. With 10 threads hitting one shard, that doubles the time each thread holds the lock.
Alternatives. Templates or generics let the compiler inline onHit and remove the dispatch entirely, at the cost of a rebuild to change policy. A runtime interface suits policy chosen from configuration. Either way, the expensive part to avoid is calling user code under the lock.
Failure modes and detection. A victim() that scans is O(n) and appears as an eviction latency spike when the cache is full, so time eviction separately. A policy and map that disagree about membership after a race cause a double eviction or a leak. Detect it with an invariant check that policy size equals map size, run in tests and sampled in production.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-42In an elevator controller, what safety rule must the door state machine enforce before it lets the car start moving?
The car may not start moving until the doors are both closed and locked, and that condition has to come from the door hardware itself. A closed switch only says the panels have met. A locked switch says the latch is engaged, so the panels cannot be pushed apart by a passenger or by the car starting to move. The motor command is gated on the locked signal, not on the controller having previously commanded the doors to close.
The reverse guard matters as well. The doors may only open when the car is stopped inside the door zone at a landing. Outside that zone, or while the car is moving, an open command must be rejected even if a passenger presses the button.
A small state machine makes the guard hard to bypass. Direction and door status are separate concerns, but motion states are only reachable through the locked check.
| State | Doors | How it is entered |
|---|---|---|
IDLE | Closed and locked | No assigned stop, or doors have just locked |
MOVING_UP | Closed and locked | Locked signal true, target above current floor |
MOVING_DOWN | Closed and locked | Locked signal true, target below current floor |
DOORS_OPENING | Opening | Car stopped in door zone |
DOORS_OPEN | Open | Fully open signal true |
DOORS_CLOSING | Closing | Dwell timer expired and door block sensor clear |
FAULT | Any | Locked signal missing after timeout, or sensor disagreement |
The guard itself is a few lines, and keeping it in the car controller means dispatch logic cannot override it:
def request_move(car, target_floor):
if not car.doors_locked:
return "DENIED"
if car.speed_mps != 0:
return "DENIED"
if target_floor > car.floor:
car.state = "MOVING_UP"
elif target_floor < car.floor:
car.state = "MOVING_DOWN"
else:
return "DENIED"
return car.stateTrace that code for a car at floor 3, speed 0, with a target at floor 6:
| Step | Input | Result |
|---|---|---|
| 1 | doors_locked = True, speed_mps = 0, target 6 | Both checks pass, state becomes MOVING_UP |
| 2 | Same car, but doors_locked = False | Returns DENIED, state unchanged |
| 3 | Car reaches floor 6, speed drops to 0 | Motion ends, DOORS_OPENING becomes legal |
Concrete timing is what makes this testable in an interview. The figures below are labelled example values for a typical passenger lift, not a claim about a specific code: dwell time 4 seconds before closing, close timeout 12 seconds, maximum 3 reopen cycles at one landing, and rated speed 1.6 m/s.
Worked arithmetic on those example values shows why the thresholds are set where they are. Assume a 3.2 m floor height, acceleration of 0.8 m/s², and a 1,100 mm door opening at 0.5 m/s. Time to accelerate to rated speed is 1.6 / 0.8 = 2.0 seconds, covering 1.6 m. The remaining 1.6 m to the next floor takes 1.0 second at cruise, so a one-floor trip is about 4.0 seconds including deceleration. Door opening takes 1,100 / 500 = 2.2 seconds, and closing takes a similar 2.2 seconds. A full stop cycle is therefore roughly 4 seconds dwell + 2.2 seconds close + 4.0 seconds travel = 10.2 seconds, before any reopen.
That arithmetic sets the fault thresholds. If the locked signal has not arrived within the 12 second close window, which is about 5 times the normal 2.2 second closing time, the controller drops to FAULT and removes the car from service. Retrying the motor would turn a sensor fault into a moving car with unlatched doors. If the block sensor keeps reopening, the cap of 3 cycles bounds the worst case at 3 × (4 + 2.2) = 18.6 seconds of door activity at one landing, then faults the car and raises an alarm, instead of holding the car indefinitely while passengers keep pressing the button.
Commissioning thresholds need numbers too, again as example values to state in an interview and then confirm against the actual lift specification: speed treated as zero only below 0.02 m/s, locked signal debounced for 50 ms before it is trusted, drive enable dropped within 100 ms of the locked signal opening, and controller scan at 10 ms so the software check adds at most 1 scan, or 10 ms, to that 100 ms hardware path. A candidate who can quote 0.02 m/s, 50 ms, 100 ms and 12 seconds, and explain that the 12 seconds is roughly 5 times normal closing time, has given the interviewer something checkable.
Two failure modes are worth naming. First, a door that closes but never reports locked. That is a timeout and a fault, as above. Second, a false locked signal, for example a shorted contact or a misaligned switch. A single contact can fail in the dangerous direction, reporting locked when the latch is not engaged.
That leads to the trade-off between interlock designs:
| Design | What it costs | What it catches | When it is acceptable |
|---|---|---|---|
| Single locked contact, checked in software | Lowest parts and wiring cost, fastest to commission | A door that is simply not closed | A bench rig or prototype with no passengers, where a wrong move costs a test run, not an injury |
| Redundant contacts wired in series, hardwired into the drive enable | More contacts, alignment work, and nuisance trips if one contact is marginal | One shorted or welded contact, because the series path still opens | The normal choice for a passenger lift, where the failure must not depend on software running correctly |
| Dual-channel monitored interlock, with commanded position compared against feedback | Highest cost, needs diagnostics and proof testing | Sensor disagreement, a stuck contact, and a mismatch between what was commanded and what the hardware reports | Higher speed or higher traffic lifts, where a nuisance fault is expensive but a silent false locked signal is worse |
Software checks alone are the cheapest alternative and they are easy to change, but they share a failure mode with the rest of the controller. A software bug, a stuck output, or a bypass left in for maintenance can all defeat them. A hardwired series path fails safe when power is lost, which is why production designs put the hardware interlock in the drive enable and keep the software state machine as a second layer, not as the only layer.
Dispatch sits above this. It assigns hall calls to cars based on distance, queued stops, and whether a car is travelling toward the call, and it runs on new calls and state changes rather than on a timer. With, for example, 4 cars and 20 queued calls, a naive reassignment on every call is 4 × 20 = 80 distance evaluations, trivial next to the 100 ms interlock budget. A poor assignment costs waiting time. A bypassed door interlock can injure someone. That difference in consequence is why the locked check lives at the bottom of the stack, in the car controller, where nothing above it can talk the car into moving.
Follow-ups an interviewer is likely to ask: what happens on power loss mid-travel, how do you detect a welded contact, and how do you prove the interlock during commissioning. The answers are the same guard in different clothes. On power loss the drive enable drops and the brake applies. A welded contact is caught by comparing the two channels and by the close timeout. Commissioning means physically holding the door off the latch and confirming the car will not move, not just reading the state machine on a screen.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-43A logger has levels and fans each record out to several sinks such as console, file and a remote shipper. Would you model the sinks as observers of the logger or wrap the logger in decorators, and how do you keep the sink list safe while threads log and sinks are added or removed?
The 90-second answer
I'd use observers for the fan-out and decorators only for per-sink concerns. First I'd confirm the assumptions: sinks change at config reload, not per request; logging is hot, several thousand calls per second per thread; and one slow sink must not stall the others.
The logger is the subject. Each sink implements one method, accept(Record), and registers with the logger. The level check happens once, in the logger, before fan-out, so a DEBUG record nobody wants costs one integer comparison. Decorators fit when a concern wraps a single sink: a sampler, a redactor, or a batching buffer around the remote shipper. Stacking decorators around the logger itself makes every wrapper pay its own level check and makes it impossible to say which sinks received a given record.
For the sink list, I'd publish an immutable array through an atomic reference. Readers take a snapshot with no lock. Writers copy the array and swap it in. With single-digit sink counts and rare writes, the O(n) copy per change is nothing.
final class Logger {
private final AtomicReference<Sink[]> sinks = new AtomicReference<>(new Sink[0]);
private volatile int minLevel;
void log(Level lvl, String msg) {
if (lvl.ordinal() < minLevel) return;
Record r = new Record(lvl, msg, System.nanoTime());
for (Sink s : sinks.get()) {
try { s.accept(r); }
catch (RuntimeException e) { droppedCount.increment(); }
}
}
void addSink(Sink s) {
sinks.updateAndGet(old -> {
Sink[] n = Arrays.copyOf(old, old.length + 1);
n[old.length] = s;
return n;
});
}
}| Option | Reader cost | Writer cost | Verdict here |
|---|---|---|---|
synchronized around fan-out | serialises all threads | cheap | throughput capped by slowest sink |
| read-write lock | shared, but still contended on the lock word | exclusive | fine, but more moving parts |
| copy-on-write snapshot | no lock | O(n) copy | chosen |
| per-sink bounded queue | enqueue only | cheap | needed for slow sinks |
Worked numbers (hypothetical). Three sinks at 30 µs each, 16 threads. Holding one lock across fan-out serialises the work: 90 µs per record gives about 11,000 records per second in total, however many cores exist. With a snapshot, each thread pays its own 90 µs and the cap is set by the slowest sink's own throughput.
Failure modes
- Re-entrant logging. The remote shipper logs its own retry failures through the same logger. With a lock, the thread deadlocks against itself. With snapshots, the call recurses until the stack overflows. Guard with a thread-local flag and divert the nested record to stderr or a counter.
- Blocking sink. A 50 ms synchronous write on the caller thread caps that caller at 20 records per second. Put a bounded queue in front of any sink that does I/O, drop with a counter when full, and alert on queue depth and drop rate.
- One sink throwing. Catch per sink. A single try around the loop silently starves every sink after the failing one.
- Cross-sink ordering. Two threads can reach different sinks in different orders. If the file and the shipper must agree, assign a sequence number inside
log()before fan-out. - Stale snapshot. A removed sink can still get one record after removal. That is acceptable for logging; say so explicitly rather than claiming a hard cutoff.
So: observers for fan-out, decorators for per-sink policy, a copy-on-write snapshot for the list, and a queue for anything that blocks.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-44Your checkout class builds its own payment gateway client and reads the system clock inside its methods. Explain what injecting those dependencies buys you in unit tests, and when a plain constructor argument is the better choice.
The 90-second answer
Dependency injection means a class receives its collaborators from outside instead of constructing them or reaching for a global. For checkout, that means Checkout(gateway, clock, orders) instead of new StripeClient() and datetime.now() buried in charge(). The payoff is a seam: a test can hand in a fake gateway that records calls and returns a scripted receipt, and a fake clock that sits at a fixed instant. No network, no sleeps, no monkeypatching, and the test fails for one reason only.
The second payoff is that the dependency list becomes part of the signature. A reader sees everything Checkout needs, and an object cannot be built half-configured.
class Checkout:
def __init__(self, gateway, clock, orders):
self._gateway, self._clock, self._orders = gateway, clock, orders
def place(self, cart, token):
receipt = self._gateway.charge(cart.total_cents, token)
self._orders.save(cart.id, receipt.id, self._clock())
return receipt
class FakeGateway:
def __init__(self): self.calls = []
def charge(self, amount, token):
self.calls.append((amount, token))
return Receipt("r_test", ok=True)A test builds Checkout(FakeGateway(), lambda: FIXED_NOW, InMemoryOrders()) and asserts on calls. Nothing else is needed.
When a plain constructor is the better choice
Injection is for things with behaviour you need to control: I/O, time, randomness, external policy. Values are not injected. A Money type, a parsed config struct or a list of line items should arrive as plain data, because faking them tests nothing and adds a parameter for no gain.
| Collaborator | Decision | Reason |
|---|---|---|
| payment gateway, DB, queue | inject behind an interface you own | I/O, must be faked |
| clock, random source | inject as a callable | nondeterminism |
Money, Address, config struct | plain value | no behaviour to swap |
| one pure helper, one implementation, no I/O | construct directly | an interface would exist only for tests |
Do not put an interface in front of every class to make tests possible. If a class has one implementation and no I/O, the interface is ceremony.
Trade-offs and failure modes
Constructor injection makes the dependency count visible. Six or more parameters usually means Checkout is doing two jobs, so split it before reaching for a container. Containers add lifetime rules: a singleton that captures a request-scoped session will hold a closed connection after the first request. You detect that as intermittent errors that only appear under load, and the fix is to resolve scoped dependencies per request.
The classic regression is a new added inside a method during a later change. The unit tests still pass, but the suite starts calling the real gateway. You catch it by running tests with network disabled, or by a lint rule that forbids construction of I/O types outside the composition root.
Wire everything in one composition root at process start. Scattered construction is what DI was meant to remove.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-45Your payment router has an if/else on provider name in charge(). Product wants a 3DS step-up for one provider and a 7-day refund window for another. Which SOLID principle does this violate, and how would you restructure it so the next provider does not touch the router?
The 90-second answer
Open/Closed. The router is shared by every provider, so each special case is a new branch in code that all charges pass through. Adding a provider means editing and retesting the path that already serves the others.
The fix is to move the variation behind an interface the router depends on. Each provider adapter implements charge() and refund() and carries its own quirks: the 3DS step-up runs inside its charge(), and the 7-day window is enforced inside its refund(). The router only calls the interface.
class Provider(Protocol):
name: str
def charge(self, req: ChargeRequest) -> ChargeResult: ...
def refund(self, ref: str, cents: int) -> RefundResult: ...
class Router:
def __init__(self, providers: dict[str, Provider]):
self._providers = providers
def charge(self, provider: str, req: ChargeRequest) -> ChargeResult:
return self._providers[provider].charge(req)Trade-off. A capability flag such as '3ds' in a set keeps one interface but moves the conditional into callers. Use flags when the router must decide something, such as whether to show a step-up screen before calling. Use adapter overrides when the difference is internal to the provider. Splitting into role interfaces costs more types but turns a missing method into a compile-time error.
| Symptom | Principle | Fix |
|---|---|---|
if provider == 'x' in the router | OCP | adapter behind Provider |
| a caller must know which provider needs step-up | leaking detail | capability flag, or return a requires_action result |
| an adapter raises on a valid call | LSP | split refund into its own interface |
Detection. Grep the router and checkout for provider-name comparisons. Each hit outside an adapter is a violation. Then add a fake fourth provider in a test. If the router or its tests must change to accept it, the abstraction still leaks.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-46A vending machine has coin, select and cancel inputs. Why store one state value rather than several boolean flags such as hasCredit and dispensing?
The 90-second answer
One state value can only hold one of the legal states, so the machine cannot be in a combination that the design forbids. Each boolean doubles the number of combinations the code has to think about. Three flags give 2^3 = 8 combinations, and most of them mean nothing for a vending machine. Nothing in the type system stops dispensing = true while hasCredit = false, so every method has to check for impossible pairs, and one missed check takes money without dispensing.
The enum version
The machine has four states: Idle, HasMoney, Selected, Dispensing. Each input is looked up against the current state:
| State | Accepts | Rejects |
|---|---|---|
| Idle | coin | select, cancel, dispensed |
| HasMoney | coin, select, cancel | dispensed |
| Selected | cancel, dispensed | coin, select |
| Dispensing | dispensed | coin, select, cancel |
A rejected input returns a typed error with the current state attached, so the UI can say "insert money first" and the logs show the sequence that led there. A rejection is a decision, not a silent drop.
Where flags still show up
Flags are fine for properties that really are independent, such as lightOn or doorOpen on the same machine. The rule is simple: if two flags are only meaningful together, they belong in one state.
Failure modes to name
The classic bug is cancelling from HasMoney without refunding, so test that transition on its own. The second is a dispensed callback that fires while a select is still being processed. Guard transitions with a lock or a single event queue, so the state is read and written as one step.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-47Your queue has capacity 1, several producers and consumers, a close() that must wake everyone, and take(timeout). Can a notify_one be consumed by a consumer that then times out and leaves the item stranded? Show the interleaving and the fix.
The 90-second answer
Yes. A notify_one is a claim on one waiter, and a waiter that returns for another reason still holds that claim. If a consumer's wait_until returns timeout and the code returns nullopt without re-reading the queue, the item stays in the buffer, the signal is spent, and another consumer sleeps until its own deadline. The fix has two parts: test the predicate on every return path, and if a thread leaves while the queue is non-empty, pass the signal on with notEmpty.notify_one(). Close needs its own rule: set closed under the lock and call notify_all on both condition variables, so no waiter is left holding a signal that cannot be delivered.
The stranded-signal trace. Capacity 1, consumers C1 and C2 both blocked on notEmpty, producer P.
| Step | Thread | Action | State |
|---|---|---|---|
| 1 | C1, C2 | wait_until(deadline) on notEmpty | q = [] |
| 2 | P | put(x) pushes, notify_one wakes C1 | q = [x] |
| 3 | C1 | blocked re-acquiring mutex, deadline passes | q = [x] |
| 4 | C1 | naive code: if (wait_until(...) == timeout) return nullopt; | q = [x], C1 gone |
| 5 | C2 | still waiting, no signal pending | q = [x] |
C2 sleeps with an item present. Nothing will notify it until the next put, so a consumer with a long deadline can wait far longer than the item has been available.
The fix.
std::optional<T> take_for(std::chrono::milliseconds d) {
std::unique_lock<std::mutex> lk(m);
const auto deadline = std::chrono::steady_clock::now() + d;
while (q.empty() && !closed) {
if (notEmpty.wait_until(lk, deadline) == std::cv_status::timeout
&& q.empty() && !closed)
return std::nullopt;
}
if (q.empty()) return std::nullopt; // closed and drained
T v = std::move(q.front());
q.pop_front();
notFull.notify_one();
return v;
}The loop re-tests the predicate after every wakeup, including a timeout. If the timeout fires while q is non-empty, the loop keeps going and takes the item, so the spent signal never strands anything. If a thread must leave with items still present (for example, a timed-out path that returns through an error branch), it calls notEmpty.notify_one() before returning so another waiter takes over.
Close and producers. close() sets closed = true under the mutex and calls notify_all on notFull and notEmpty. Blocked producers wake, see closed, and return an error. Consumers drain what remains, then see empty plus closed and return. Without the closed term in the producer's loop, a producer blocked on a full queue sleeps forever at shutdown.
Failure modes to test. Run the tests with forced spurious wakeups and with deadlines that expire during a put. Check that the count of items taken plus items left equals the count put, and that no consumer waits past its deadline while the queue holds an item. A wait_for timeout that never re-reads the state is the usual cause of lost work in production queues.
The wait_until form with the predicate lambda handles the loop for you. The explicit form is shown because the timeout branch is where the bug lives.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-48Your URL shortener issues base62 keys and must never give two URLs the same key. Compare a random key with a counter encoded in base62 on their collision risk and what you must store to enforce uniqueness, and say which one you would ship.
The 90-second answer
I would ship the counter, encoded in base62. Random keys can collide, and the cost of handling that shows up on every write. A counter gives distinct keys by construction, and the only thing I have to protect is that the counter never hands out the same value twice.
Assumptions: one key per long URL is not required, the key length is fixed at six characters, and the service runs several app servers. Six base62 characters give 62^6 = 56,800,235,584 values, which covers a billion keys with room to spare. Five characters give 62^5 = 916,132,832, which is short of a billion, so the length decision is already made before the collision question even starts.
Random keys. Draw six characters at random and insert with a unique constraint. The probability that a new key collides with one of n existing keys is about n / 62^6. With a billion stored keys that is about 1.8%, so roughly one in fifty new inserts hits a collision and must retry. Retries grow as the space fills, and the expected number of collisions across the whole lifetime of the table follows the birthday approximation n²/(2N): about 8.8 million for n = 10^9 and N = 5.7 × 10^10 (hypothetical volume, labelled as such).
Counter, base62 encoded. Take an integer ID and encode it. Base62 is a bijection on non-negative integers, so distinct IDs always give distinct strings. Uniqueness reduces to: does the ID source ever repeat? A single sequence never does. Across servers, each one leases a block (say 1,000 IDs) with UPDATE counter SET next = next + 1000 RETURNING next and hands out IDs from its block in memory. A crash wastes the unused part of the block, which costs gaps, not duplicates.
ALPHABET = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
def encode(n: int) -> str:
if n == 0:
return ALPHABET[0]
out = []
while n:
n, r = divmod(n, 62)
out.append(ALPHABET[r])
return "".join(reversed(out))| Scheme | Collision risk | What enforces uniqueness |
|---|---|---|
| random 6-char | about 1.8% per insert at 10^9 keys | unique index plus retry loop |
| counter, base62 | none by construction | atomic lease plus unique index as a backstop |
Trade-offs. Sequential keys let anyone enumerate neighbours (aaaaab, aaaaac) and estimate your volume. If that matters, pass the ID through a keyed bijection, such as a Feistel network over the 36-bit ID space, before encoding. It stays one-to-one, so uniqueness is preserved. An unkeyed shuffle is not safe, because anyone who learns it can invert it.
Failure modes. Overlapping leases would duplicate keys silently. The unique index turns that into a constraint violation rather than a redirect to the wrong URL. A non-atomic lease update is the usual cause, so check the statement is a single atomic UPDATE ... RETURNING. Alert when the issued maximum passes about 80% of the space for the chosen length, which is the point to move to seven characters.
So: counter plus base62, a unique index as the safety net, and a keyed permutation only if keys must not look sequential.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-49Your rate limiter runs on 40 nodes behind a load balancer and must cap each client at 100 requests per minute across the fleet. Compare a central Redis counter with local per-node counters. What does each give up, and how far can a local counter drift from the real limit?
The 90-second answer
I'd confirm two things first: whether the limit is fixed-window or sliding, and whether the limiter should fail open or closed when Redis is unreachable. Those decide much of the design. A central Redis counter enforces the limit almost exactly, at the cost of one network hop per request. Local counters remove the hop but enforce the limit only approximately, and the error depends on how the load balancer spreads each client's traffic across nodes.
Central counter. One atomic script does the check and the increment, so two nodes can't both take the last slot:
local n = redis.call('INCR', KEYS[1])
if n == 1 then redis.call('PEXPIRE', KEYS[1], ARGV[1]) end
if n > tonumber(ARGV[2]) then return 0 end
return 1The key is client id plus window index. Hypothetical figures: 25,000 requests/s fleet-wide means 25,000 script calls/s, which one Redis shard handles comfortably. An in-region round trip of about 0.5 ms raises p50 by roughly that much. The cost is a shared dependency: when Redis is slow or fails over, every request either waits or is decided without the counter. Detect it with a p99 on the script call and a count of fail-open decisions.
Local counters. Divide the quota evenly: 100/40 = 2.5, so each node enforces 3. Two errors follow. If one client's requests land on only 5 nodes, its effective cap is 15, far below quota. If they spread across all 40, the fleet can admit up to 120, a 20% overshoot. Under uniform random routing, per-node counts are roughly Binomial(100, 1/40): mean 2.5, standard deviation about 1.6. Check your load balancer's real distribution before trusting either extreme.
Leases as a middle ground. Each node borrows blocks of L tokens from Redis and spends them locally. Over-admission is bounded by tokens held by nodes that die or stall. With 40 nodes and L = 5, that is up to 200 extra requests, double the limit, so leasing does not help at this scale. It works when the limit is large relative to the fleet, for example 100,000 per minute with L = 50 gives 2,000 slack, about 2%.
| Design | Added latency | Accuracy | Main failure | How to detect |
|---|---|---|---|---|
| Central Redis script | about 0.5 ms p50 | exact to in-flight requests | Redis outage or failover | p99 of script call, fail-open count |
| Local limit/N | none | under-admits on skew, up to 20% over | one client clustered on few nodes | admitted per client vs. quota in logs |
| Local with leases | none on hot path | over-admit bounded by N x L | nodes dying holding tokens | unused tokens at lease expiry |
What I'd pick. For abuse protection at high limits, local counters with leases keep p99 flat and are accurate enough. For hard quotas at low limits, I'd accept the Redis hop, shard keys by client id, and decide the fail-open policy explicitly before launch.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-50In consistent hashing, what is the expected fraction of keys that move when a node joins a ring that already has N nodes?
The 90-second answer
About 1/(N+1). Keys and nodes share one hash ring, and a key belongs to the first node clockwise from its hash. A joining node takes over only the arc between itself and its predecessor, so on average it gains a share equal to one of N+1 equal slices. Going from 10 to 11 nodes moves about 1/11, roughly 9%, of keys.
Modulo hashing has no such bound. With hash(key) % N, going from 10 to 11 nodes changes the remainder for about 10/11, roughly 91%, of keys. That is why consistent hashing is used for caches and sharded stores where resizing must not cause a miss storm.
Why the rule holds
A join inserts new points on the ring. Only keys whose hash lands in the new arcs change owner. Every other key keeps the same clockwise successor, because no other point moved.
Worked arithmetic (hypothetical load)
Assume 10 nodes, 1,000,000 keys, and one new node.
| Scheme | Expected keys moved |
|---|---|
| modulo, 10 to 11 | 10/11, about 909,000 |
| consistent hashing, 10 to 11 | 1/11, about 91,000 |
Virtual nodes
With one point per physical node, arc lengths vary a lot, so one node can own several times its fair share. Giving each node about 150 virtual points makes the load much more even. The expected moved fraction stays 1/(N+1); virtual nodes change how evenly the keys are spread, not how many move.
When not to use it
If the node count is fixed, modulo is simpler and faster. If placement must follow heterogeneous capacity exactly, an explicit partition map from a coordinator gives tighter control.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-51You shard a key-value store by hash of the key across 64 partitions. One key receives 30% of 1M writes per second. Why doesn't hashing fix it, how would range partitioning behave differently, and what would you change?
The 90-second answer
No partitioning function fixes one hot key, because any function maps a key to exactly one place. Hash and range partitioning differ on the other skews. Hash spreads distinct keys evenly but cannot spread a single key. Range keeps neighbours together but sends sequential keys to one range. The fix for a single hot key is to split the key itself, and that moves the cost onto reads.
Assumptions: 64 partitions, replication factor 3, 1M writes/s total, one key taking 300k/s, opaque string keys.
Hash partitioning. partition = hash(key) mod 64 (or consistent hashing with virtual nodes). The other 700k/s spread across 64 partitions at about 10.9k/s each. The hot key's partition takes 300k + 10.9k, about 311k/s, roughly 28 times its neighbours. Adding partitions does not help, because the hot key still lands on one partition at 300k/s.
Range partitioning. The same arithmetic applies to one key. It is worse for monotonic keys. If keys are timestamp-prefixed, every new write lands in the last range, even with perfectly uniform key popularity. Hash avoids that case and range does not.
| Approach | Spreads distinct keys | One hot key | Sequential keys | Range scan |
|---|---|---|---|---|
| hash | even | one partition at 311k/s | even | scatter-gather |
| range | follows key-space density | one range | last range takes all writes | contiguous |
Remedy: salting. Write to key#s, where s = rand mod N. Each sub-key hashes to a different partition. Size N from the budget, not from a guess: 300k/s divided by a 20k/s per-partition budget gives 15, so use N = 16. Each sub-key then gets about 18.75k/s.
INCR page:home -> shard(hash("page:home#" + rand(16)))
GET page:home -> fan out 16 GETs, sum the resultsThe read cost moves to the reader. The logical read is now 16 requests, and its p99 tracks the slowest of the 16 responses. A read-hot key is better served by its replicas, or by a cache in front, than by salting.
Detection. Watch per-partition QPS and the top-k writers. An exact per-key counter costs memory proportional to the key space, so use a sampled heavy-hitter sketch such as Space-Saving on the write path.
Failure modes.
- Salting a last-write-wins
SETbreaks, because the sub-keys diverge and no read can pick the right value. It works only for mergeable values such as counters, sets or CRDTs, or where each sub-key holds a versioned value and the reader picks the highest version. - Fan-out reads amplify tail latency. Track the p99 of the fan-out, not the mean of a single get.
- Rebalancing a range that holds the hot key does not help, since splitting it still leaves the key in one range.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-52Your read-heavy catalogue service sits in front of PostgreSQL with Redis as a cache. Compare cache-aside with write-through: where does each one produce a stale read, what does a write cost in each, and which failure mode does each invite?
The 90-second answer
Cache-aside keeps the cache as a read copy that the application fills on a miss. Write-through makes the cache part of the write path, so the key is updated before the caller returns. Cache-aside invites stale reads from a race between a refill and a write. Write-through invites divergence between cache and store when one of the two writes fails, and it makes every write pay for both.
Assumptions: one PostgreSQL table, Redis, TTL 300 s, a 50:1 read-to-write ratio.
Cache-aside read: GET key, on miss SELECT then SET key value EX 300. Cache-aside write: UPDATE the row, commit, then DEL key.
The stale race, traced:
- t0: reader A misses and reads v1 from the database.
- t1: writer B updates the row to v2 and commits.
- t2: writer B runs
DEL key. - t3: reader A, still holding v1, runs
SET key v1 EX 300.
The cache now holds v1 while the database holds v2, for up to 300 s. Deleting instead of setting on write avoids the writer overwriting with its own value, but it does not close this window. Options: keep the TTL short enough to fit the staleness budget; store a row version in the value and only write it with a compare-and-set in a Lua script when the new version is higher; or accept the window if the product allows it.
Write-through write: UPDATE the database first, then SET the cache. The order matters. If the cache is written first and the database commit fails, the cache holds a value that never existed. If the database commits and the cache write fails, the cache holds the old value until the TTL expires. Write the database first and keep the TTL as the backstop.
| Cache-aside | Write-through | |
|---|---|---|
| Stale window | refill race, or a lost DEL until TTL | failed cache SET until TTL |
| Cost per write | one DB write plus one DEL | one DB write plus one SET, both synchronous |
| First read after write | one miss, one DB read | hit |
| Cache for unread keys | not written | written anyway, wasted memory |
| Dominant failure | refill race, lost invalidation | dual-write divergence, cache outage blocking writes |
Write amplification is different in each. Cache-aside moves the cost to the next read: a hot key that gets 1,000 writes per minute causes up to 1,000 refill reads per minute on the database, which can be more load than the writes themselves. Write-through pays on every write, including keys nobody reads again.
Which to ship: cache-aside for a read-heavy catalogue where a bounded stale window is acceptable, with the version guard if you can afford it. Write-through when a user must read their own write immediately and writes are a small share of traffic.
Detection: track hit ratio per key class, store updated_at in the cached value and alert on its age at read time, and sample reads against the database to measure the actual stale rate.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-53A hot cache key expires and 5,000 requests per second miss during the 200 ms recompute. Roughly how many database queries land in that window without any protection, and how does request coalescing change that number?
The 60-second answer
Without protection, every request that misses while the recompute runs goes to the database. That is arrival rate times recompute latency: 5,000 requests/s × 0.2 s = 1,000 concurrent queries. If the table tolerates about 200 concurrent queries, that is five times the limit, and the recompute itself slows down, so the window grows. A blip becomes an outage through that feedback.
Assumptions: one hot key, a single process fielding all 5,000 requests, a recompute that takes 200 ms, and no stale value kept.
Request coalescing. The first miss marks the key as in flight and runs the recompute. Every other miss for that key waits on the same result instead of querying. Backend load for the key falls to one query per 200 ms, which is 5 per second.
t=0.000 req 1 miss -> marks in-flight, queries DB
t=0.001 req 2 miss -> in-flight, waits
t=0.200 DB returns -> cache set, all waiters get value
t=0.201 req 4000 hit -> served from cacheCoalescing has a scope. Per process, it costs nothing and bounds the load at one query per node per window. With 40 nodes, the worst case is 40 concurrent queries, still far under 200. Cross-fleet coalescing needs a shared lock, which adds a round trip and a lease that must outlast the recompute, or a second leader starts while the first is still running.
TTL jitter addresses a different shape. If a batch job writes 10,000 keys with TTL 300 s, they all expire together and send 10,000 recomputes at once. Setting ttl = 300 + uniform(0, 30) spreads those expiries over 30 s, about 333 per second. It does nothing for one hot key, which expires once.
| Mechanism | Shape it fixes | Main cost |
|---|---|---|
| per-process coalescing | one hot key on one node | bounded by node count |
| shared lock | one hot key fleet-wide | extra round trip, lease tuning |
| TTL jitter | many keys written together | expiry spread |
The choice follows the failure shape: one hot key calls for coalescing, a synchronized batch calls for jitter.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-54Under least connections, what does the balancer compare when it picks a backend for a new request?
The 90-second answer
It compares the number of open connections to each backend at dispatch time and sends the request to the one with the fewest. Round robin ignores that state and cycles through backends in a fixed order. The point of the comparison is that a slow backend holds each connection longer, so its open count rises and it receives fewer new requests.
The rule is simple, but the reason it helps is worth stating: a backend's open connection count is roughly its arrival rate times its mean latency, so a backend that is slow accumulates connections and is skipped until its count drops.
Hypothetical example (3 backends, A and B at 20 ms, C at 80 ms, traffic 90 req/s)
| Policy | Req/s to A / B / C | Why |
|---|---|---|
| Round robin | 30 / 30 / 30 | fixed 1/N share regardless of latency |
| Least connections | more to A and B | C's open count is higher, so it is picked less |
The split under least connections is an illustration of direction, not a measured figure.
Limits to mention if asked
- It counts connections, not work. A long-lived WebSocket can hold one connection for minutes while doing little, so consider in-flight requests instead.
- Each balancer node counts only its own connections, so many nodes can pick the same backend at once. Power of two choices, sampling two backends and taking the one with fewer active requests, reduces this.
- A backend returning fast errors looks lightly loaded. Exclude or penalise backends with high error rates.
When round robin is fine
With similar backends and short uniform requests, round robin is even and needs no per-request state.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-55During a rolling deploy, a pod receives SIGTERM while 300 requests are in flight behind an ALB with a 60-second deregistration delay and a 30-second terminationGracePeriodSeconds. Walk me through what happens to each in-flight request, and how you would pick the drain timeout and health check interval so no request gets a 502.
The 90-second answer
The first thing I'd check is the two clocks. The ALB stops sending new requests to a target as soon as it enters the draining state, which happens when the target is deregistered. The deregistration delay is not a window of continued new traffic. It is the cap on how long the ALB waits for requests already in flight to finish before it closes those connections. With a 60 s delay and a 30 s grace period, the kubelet SIGKILLs the container at 30 s, while the ALB may still be holding open connections to it. Requests still running at that moment are reset, and the ALB reports 502s.
So the fix is an ordering and a pair of numbers that agree. The pod must stop accepting new work and exit only after its open requests are done, and the grace period must cover that tail.
What happens to the 300 requests
| Time | Event | State of the 300 in-flight requests |
|---|---|---|
| 0 s | Pod set to Terminating, SIGTERM sent | Pod keeps serving what it already has |
| 0 s | Deregistration begins on the ALB target group | ALB stops routing new requests to this target |
| 0 s to 60 s | Deregistration delay running | ALB waits for in-flight requests to finish |
| 30 s | SIGKILL if grace period is 30 s | Any request still running is reset, producing a 502 |
| 60 s | Deregistration delay expires | Any connection still open is closed by the ALB |
Hypothetical figures: the slowest legitimate request takes 4 s at p99.9, so anything past 10 s is a bug, not drain.
Choosing the numbers
Work backwards from the slowest legitimate request, S. Requests that the ALB already routed to the pod before deregistration are the ones at risk, so the grace period must outlast the longest of them:
terminationGracePeriodSeconds >= S_p999 + margin
With S = 10 s and a 5 s margin, 15 s is enough, so 30 s has room. The deregistration delay should be at least as long as S as well, so the ALB does not cut connections that the pod is still finishing. A 60 s delay is larger than needed here; it only delays the target's removal from the group and keeps the rollout slower. If the pod exits before the delay ends, the ALB handles the target as gone, which is the outcome you want.
The health check interval matters for a different reason. It governs how fast the ALB notices a target that stops answering on its own, such as a crashed process, which is not the same as a graceful drain. For a graceful deploy, deregistration does the work, so the interval should be tuned for failure detection, not drain.
Code: the drain itself (Go, net/http, 1.22)
srv := &http.Server{Addr: ":8080", Handler: mux}
go srv.ListenAndServe()
<-sigterm
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
defer cancel()
srv.Shutdown(ctx)Shutdown closes the listener and idle connections, then waits for active requests to finish. If the context expires, it returns with those requests still running. The outer timeout must be shorter than the grace period so the process exits cleanly before SIGKILL.
Failure modes to name
- Keep-alive connections. A reused connection can carry a new request after the listener closed. Setting
Connection: closeon responses while draining stops this. - Long-poll or streaming responses longer than S. They are cut at SIGKILL. Track requests open at SIGKILL time with a metric to find them.
- Readiness checks that keep passing after SIGTERM. The pod may still look healthy to other consumers, so fail readiness at the same moment the drain begins.
Trade-off
A longer grace period costs rollout speed and protects in-flight requests. A shorter one is faster but risks 502s for slow requests. Verify the choice by counting 502s from the ALB during a rollout and checking that the count is zero for requests that began before SIGTERM.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-56A user saves a new display name, then the profile page reloads from a read replica that still shows the old one. Explain how you would make that user see their own write, and what trade-off you accept against sending every read to the primary.
The 90-second answer
Replication is asynchronous, so a replica can serve state older than the primary's latest commit. Read-your-writes only has to hold for the writer, and only until the replica catches up. So I would not send all reads to the primary. I would compare two ways to scope that guarantee and pick the cheaper one that is still correct for this profile page.
Approach one: pin the writer's profile reads to the primary for a fixed window after a write, say 5 s. It is simple, needs no client state, and the primary handles only the writer's own reads. The weakness is that the window is a guess. If replay lag spikes to 8 s, the user sees the old name again after 5 s.
Approach two: take the commit position from the write and check it against the replica before reading. After the update commits on PostgreSQL 10 or later, the service reads the write's LSN and returns it to the client. On the next profile read, the service asks the replica for pg_last_wal_replay_lsn(). If the replica has replayed at or past that LSN, it serves the read. If not, it reads from the primary.
Trace with hypothetical figures: the write commits at LSN 0/3A2F100. The replica has replayed only to 0/3A2A000, about 300 ms behind. A read arrives 50 ms later carrying the token, the replay position is behind it, so the read goes to the primary and returns the new name. Once the replica replays past the token, reads go back to the replica.
| Approach | Cost | Breaks when |
|---|---|---|
| Pin writer's profile reads to primary for 5 s | simple, primary load scales with write rate | lag exceeds the window |
| LSN check against replica, primary on miss | exact, needs the token passed back to the client | token is lost, for example on a new device |
The LSN approach is exact, so I would pick it for a profile page where the stale name is visible immediately. The pinning approach is fine if the team cannot yet thread a token through the client, provided it is labelled as a time-boxed approximation.
Scope the promise honestly. This guarantees the writer's own session. Other users, and the same user on another device, may still see the old name during the lag window. Say that before the interviewer has to ask.
One failure mode to name: if the token is missing, the read silently falls back to the replica. Count reads that arrive without a token shortly after a write, so that gap shows up in metrics rather than in support tickets.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-57You shard a PostgreSQL orders table by customer_id across 16 shards. A merchant report filters on merchant_id and does not include customer_id. What does the router do with that query, why does its latency follow the slowest shard, and how would you avoid the fan-out?
The 90-second answer
The router cannot route by merchant_id, because the shard key is customer_id and the query does not name it. It sends the query to all 16 shards, each runs the filter locally, and the application merges the partial sums. That is scatter-gather. Nothing is wrong with the database here. The query simply has no shard key, so it has no single shard to go to.
The latency consequence matters more than the extra work. The merged response cannot return until the last shard answers. If each shard independently has a 1% chance of a slow response in a given window, the chance that at least one of 16 is slow is 1 − 0.99^16 ≈ 14.9%. The fan-out's tail is set by the worst shard, not the average.
Trace (hypothetical figures, 16 shards, 5 ms typical per shard):
- Shard k receives
SELECT sum(total) FROM orders WHERE merchant_id = 88 AND day = '2026-11-01'. - Each shard returns one row in about 5 ms.
- The slowest shard returns in 120 ms because of a checkpoint.
- The client sees 120 ms plus merge time, not 5 ms.
Three ways to avoid the fan-out, each with its own trade-off:
| Option | What it gives | What it costs |
|---|---|---|
Secondary index or lookup table merchant_id → customer_ids | the query routes to only the shards holding that merchant's customers | an extra write per order, and a lookup that must stay consistent |
Asynchronous copy into a reporting store keyed by merchant_id | cheap reads, one shard | reports lag the writes, and the copy needs its own reconciliation |
| Accept the fan-out, run it off the request path | no extra write path | the report is slow, so it cannot back an interactive page |
My default for a merchant dashboard is the reporting copy, because the freshness requirement for a report is usually minutes, not milliseconds. I would not use the lookup table unless merchant queries must be exact and current, since it doubles the write path for every order.
What to measure: p99 of the fan-out, and the fraction of shards hit per query. If the fan-out p99 is over budget, the fix is removing the fan-out, not adding replicas to each shard.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-58Under PostgreSQL's default READ COMMITTED isolation, two concurrent transactions each run UPDATE inventory SET qty = qty - 1 WHERE sku = 'X'. Is this single statement subject to the lost update anomaly?
The 60-second answer
No. A single UPDATE ... SET qty = qty - 1 is safe under READ COMMITTED. The read and the write happen inside one statement, and PostgreSQL takes a row lock on the matched row. The second transaction blocks until the first commits, then re-reads the current committed version of that row and applies qty - 1 to it. Both decrements land.
UPDATE inventory SET qty = qty - 1 WHERE sku = 'X';
-- two concurrent runs from qty = 5 end at qty = 3The lost update appears when the application reads qty into memory, computes the new value and writes it back as a literal. That read-modify-write spans two statements, and nothing stops the second writer from overwriting the first.
Two things to add if pressed:
- The rule holds only for the arithmetic itself. Adding a guard such as
AND qty >= 1still needs a rowcount check, because a zero-row result means out of stock. - Under REPEATABLE READ, the second transaction gets SQLSTATE 40001 instead of waiting for the new value, so the application must retry.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-59With N = 3 replicas, which R and W pairs make every read quorum overlap the last successful write, and what does that overlap fail to guarantee?
The 90-second answer
A read quorum of size R and a write quorum of size W, drawn from N replicas, must share at least one replica whenever R + W > N. With N = 3 the valid pairs are (R, W) = (2, 2), (1, 3) and (3, 1). Any two of the three nodes intersect the two-node write set {A, B}, because the only node outside it is C. So a read of two replicas always touches a node that acknowledged the last successful write. That is pigeonhole, and it holds for any choice of the two read nodes.
What the overlap does not buy is much more than candidates usually say. It does not give linearizability, it does not stop a failed write from being visible, and it does not resolve concurrent writers by itself.
Trace, W = 2, R = 2, N = 3
| Step | A | B | C | Event |
|---|---|---|---|---|
| 0 | v4 | v4 | v4 | steady state |
| 1 | v5 | v5 | v4 | write v5 acked by {A, B}, C was slow |
| 2 | v5 | v5 | v4 | read {B, C}: versions v5 and v4, pick max, returns v5 |
The read picks the highest version among the replies, and that is what makes the overlap useful. Without a version number on each replica, a read from {B, C} cannot tell which value is newer.
What it does not guarantee
-
Monotonic reads after a failed write. Suppose a write with W = 2 reaches only A and returns an error. A is now at v5 and B and C are at v4. A read of {A, B} returns v5, a later read of {B, C} returns v4, and the value appears to go backwards. The client saw an error, yet its data is readable. Quorum arithmetic says nothing about writes that never met their quorum.
-
Concurrent writers. Two clients write v5a and v5b with W = 2 each. Both can succeed on overlapping nodes, and the replicas can end up with different values at the same version number. Resolving that needs a total order (last-write-wins on a timestamp, or vector clocks with siblings), and LWW silently drops one write when clocks skew.
-
Sloppy quorums. Dynamo-style stores accept writes on nodes outside the home N set when home replicas are down (hinted handoff). Then the W nodes and the next R nodes need not intersect the home set at all. R + W > N still holds on paper, but the intersection is with the wrong set. Strict quorum is the only version where the arithmetic is a guarantee.
-
Membership change. A replica added during the write window may hold no copy, and a replica removed may hold the only copy of v5. Overlap is a property of a fixed N.
Choosing the pair
W = 3, R = 1 makes reads cheap and writes fail whenever any replica is down. W = 1, R = 3 makes writes available and reads expensive and sensitive to a single slow node. (2, 2) balances the two and tolerates one failure on either path. For a 1-node failure, (2, 2) keeps both reads and writes available. (3, 1) and (1, 3) each lose availability on one path as soon as one node is down.
In Cassandra terms, QUORUM with RF = 3 is floor(3/2) + 1 = 2, which is the (2, 2) case. Check the current consistency docs before quoting that for a specific version, since per-operation levels and LOCAL_QUORUM behaviour change across releases.
What I would check in a design review
The monitor for lost overlap is a read that returns a version older than the newest acked write, sampled from a canary key. Keep the version in the value, track acks per write, and alert on a non-monotonic read rate above zero.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-60Your order-status service runs in two regions with asynchronous replication, and the link between them drops for 40 seconds. What does CAP force you to choose during that partition, and what does PACELC add for the hours when no partition exists?
The 60-second answer
CAP only bites during a partition. Once the link between regions drops, a replica in region B cannot learn about writes accepted in region A, so B must either refuse some requests or answer with data it cannot confirm is current. The choice is between consistency (C) and availability (A) on the side that is cut off. Partition tolerance (P) is not optional on a real network, so the real decision is which side gives way.
PACELC adds the case that CAP ignores: Else, when there is no partition, you still trade latency (L) against consistency (C). A strongly consistent write needs acknowledgement from a second region, so the cost is paid on every request, not only during failures.
Mechanism, with a trace
Assume async replication with a typical lag of 150 ms (hypothetical figure for this example).
| Moment | Region A | Region B |
|---|---|---|
| t=0 | status=shipped committed, ack in 5 ms | still status=paid |
| t=0.15 s | replicated | status=shipped |
| t=10 s | link drops | cannot receive writes |
| t=12 s | accepts new writes | read returns paid (stale) or 503 |
Under the CP choice, B rejects reads that need the latest state (503 with upstream_unavailable). Under the AP choice, B serves its last applied state and tags the response with the replication watermark so clients can see how old it is. The stale window is bounded by the lag, which is why you alert on replication lag rather than on errors.
Normal operation under PACELC:
| Setting | Normal write p50 (hypothetical RTT 70 ms) | Read after write |
|---|---|---|
| Async commit (EL) | about 5 ms | may miss own write |
| Sync cross-region (EC) | about 75 ms (5 ms + 70 ms RTT) | always current |
Which side I would pick
For order status I choose AP during the partition and async replication in normal operation. A customer seeing paid for 40 seconds is annoying but harmless. Each state transition carries a version, and reconciliation keeps the highest version, so the replicas converge once the link returns.
I would not make that choice for inventory decrements or payment capture. Those need a single writer per key, or a CP quorum, because two regions each selling the last unit is a real loss.
Failure modes to name
- Last-writer-wins on wall clocks silently discards a newer status when clocks skew. Use version numbers from the owning writer.
- Users who write in A and read in B see their own write vanish. Pin a session to the primary for a few seconds after a write, or send reads with a minimum version.
- Partition duration is invisible without a metric. Track replication lag per region and the count of requests served past a staleness budget.
The short version for the interview: CAP tells you what to give up during a split, PACELC tells you what you pay every day to avoid giving it up.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-61A consumer reads at-least-once deliveries from a queue and writes an order status update to PostgreSQL. How do you make a redelivered message harmless using a deduplication key, and where does the dedupe check have to sit relative to the write?
The 90-second answer
At-least-once means the broker redelivers whenever it doesn't see an ack, so the same message can arrive twice. The consumer makes a redelivery harmless by recording a deduplication key in the same database transaction as the write. The key should come from the producer (for example message_id), not from the delivery tag, because the tag changes on every redelivery.
The check has to be the unique insert itself, inside the transaction that applies the change. A read-then-write (SELECT to see if the key exists, then insert) races: two consumers both see no row and both apply the effect.
with db.transaction() as tx:
inserted = tx.execute(
'INSERT INTO processed_messages (dedup_key) VALUES (%s) '
'ON CONFLICT DO NOTHING', (message_id,)).rowcount
if inserted == 1:
tx.execute('UPDATE orders SET status = %s WHERE id = %s',
(new_status, order_id))
queue.ack(message) # only after commit returnsTrace: delivery 1 inserts the key, updates the order, commits, and then the ack is lost. Delivery 2 arrives 30 s later, the insert conflicts, rowcount is 0, and the consumer acks without touching the order. If the process crashes before commit, no row exists, so the redelivery applies the update once.
| Approach | Crash before commit | Two consumers, same message | Main cost |
|---|---|---|---|
| Unique insert in the same transaction | rolls back, safe | unique index serialises them | dedupe table grows |
SELECT then INSERT | rolls back, safe | both can apply the update | race under concurrency |
Redis SETNX, then the write | key set, write lost | safe | message dropped on crash |
Why the ack goes last
Ack after the commit returns. If you ack first and the process dies, the broker never redelivers and the update is lost. Acking after commit means a crash only ever causes a redelivery, and the dedupe row turns that into a no-op.
Where it breaks
- Effects outside the database. An email or a payment call can't join your transaction. Pass the dedup key to the downstream as its idempotency key, and only rely on this if the downstream honours it.
- Dedupe table size. Keep rows at least as long as the broker can redeliver a message. If you expire them sooner, a late duplicate looks new.
- Slow processing. If work outlasts the visibility timeout, a second consumer picks the message up. The unique insert still blocks a double update, but the slow consumer may ack a message it no longer owns.
Detection: count ON CONFLICT hits per queue. A steady rise means redeliveries are increasing, which usually points to visibility timeouts that are too short.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-62A topic has 6 partitions and one consumer group has 10 consumers. How many consumers in that group read a given partition, and what ordering guarantee does that give you?
The 60-second answer
Within one consumer group, each partition is assigned to exactly one consumer at a time, so no two consumers in the group read the same partition. With 6 partitions and 10 consumers, 4 consumers sit idle. Records with the same key always hash to the same partition, and that one consumer handles them in offset order. That is the guarantee: per-partition ordering. It is not global ordering across partitions, and it caps the group's parallelism at 6.
A queue and pub-sub differ in what they split. A consumer group splits work: each message goes to one consumer in the group, so adding consumers raises throughput up to the partition count. Pub-sub copies work: every subscription receives every message, so adding subscribers multiplies deliveries instead of dividing them. If you need N independent systems to each see the full stream, you create N consumer groups, not N consumers in one group.
Trace, with group billing on 6 partitions: partition 0 to c1, partition 1 to c2, through partition 5 to c6, and c7 to c10 idle. Key acct_17 hashes to partition 3, so c4 reads every event for that account in offset order. Now add partitions to scale past 6. The group rebalances, and acct_17 may hash to a new partition. Events already in flight on the old partition can then be processed out of order with respect to new ones, so drain or pause the group before you change the partition count.
Scaling consumers therefore means scaling partitions first. Partition count can be increased but not decreased without recreating the topic, and changing it changes the key-to-partition mapping for the hash partitioner. Plan the count for peak consumer count with headroom, because it is the ceiling on useful parallelism and the hardest knob to change later.
Failure mode to name: a slow consumer on one partition creates lag on that partition only. Watch per-partition lag, not the group total, or a single hot key hides behind a healthy average.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-63Your service has a bounded queue in front of a worker pool. When the queue fills, what signal tells you to block the producer, drop the newest item, or shed load upstream, and what does each choice cost the caller?
The 90-second answer
A bounded queue is a promise about memory. Once it is full, something has to give, and the choice is about who absorbs the wait: the producer, the item, or the caller further upstream. I pick by asking whether the work is still worth doing and whether the caller can see the refusal.
The signals that drive each choice:
- Block when the producer is in-process and its rate is bounded by the same resource. Trigger:
putwaits longer than a budget, say 50 ms at p99. Cost: the producer's thread or coroutine is parked, so latency climbs upstream and threads pile up if the wait is unbounded. - Drop newest (reject at enqueue) when items are idempotent or cheap to regenerate, such as metrics or cache warms. Trigger: queue depth at capacity for more than one sampling interval. Cost: silent data loss unless you count it.
- Drop oldest when only the freshest state matters, such as sensor readings or price ticks. Cost: consumers process stale items last and never see some values.
- Shed load upstream (return
503or429withRetry-After) when the caller can retry elsewhere or back off. Trigger: queue wait exceeds the request deadline, not just queue length. Cost: the caller must handle the error, and retry storms can amplify the overload.
Why wait time beats queue length. A queue at capacity 1000 with a service time of 2 ms holds about 2 s of work. A queue of 10 with a 2 s service time holds 20 s. Length alone hides that. I track the age of the head item, or estimate wait as depth / throughput, and compare it to the deadline. If the head has already waited longer than the caller's timeout, executing it is pure waste: drop it or fail fast before doing the work.
Trace. Capacity 100, consumers drain 500 items/s, producers offer 800 items/s. Net fill is 300/s, so the queue is full in 100/300 ≈ 0.33 s. Blocking now throttles producers to 500/s, and nothing is lost but latency rises to whatever the producers tolerate. Dropping keeps latency bounded at roughly 100/500 = 200 ms but loses 300 items/s. Shedding at the edge returns 300/800 = 37.5% of requests as 503, which the caller can retry.
Failure modes to name.
- Blocking a thread that holds a lock the consumer needs: deadlock. Use timed offers and never block while holding a lock.
- Dropping without a metric: nobody notices until a reconciliation job fails. Emit a counter per drop reason.
- Shedding at the wrong layer: rejecting after the expensive work is done wastes capacity. Check admission before parsing and fan-out.
When not to bound. If an unbounded queue is only safe because producers are rate-limited elsewhere, state that dependency explicitly. Otherwise the bound is the only memory guard you have.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-64A service updates a row in Postgres and then publishes an event to Kafka in the next line of code. Explain why a crash between the two can lose the event or duplicate it, and how a transactional outbox fixes the lost case.
The 90-second answer
The database and Kafka are two systems with no shared commit. Whatever order the code uses, a crash between the write and the publish leaves them disagreeing. Publish first and a rollback leaves an event for a change that never happened. Write first and a crash before the send loses the event. Retrying the publish after a timeout can also duplicate it, because the first send may have landed.
A transactional outbox removes the lost-event case. The event row is written in the same Postgres transaction as the state change, so both commit or neither does. A separate relay then publishes outbox rows to Kafka and marks them sent. The relay can crash after publishing and before marking, so the same event can go out twice. The outbox therefore gives at-least-once delivery, and the consumer must dedupe.
Trace without an outbox
1. UPDATE charges SET status='captured' WHERE id=77; -- commits
2. producer.send(ChargeCaptured{id:77}) -- process crashes hereAfter the restart nothing retries step 2. Downstream never learns the charge was captured. If the send timed out instead of crashing, the retry may publish a second copy.
Trace with an outbox
BEGIN;
UPDATE charges SET status='captured' WHERE id=77;
INSERT INTO outbox(id, aggregate, payload, created_at)
VALUES (uuid, 'charge:77', '{"type":"ChargeCaptured"}', now());
COMMIT;If the process dies before COMMIT, neither row exists and the charge is still uncaptured, so no event is owed. If it dies after COMMIT, the outbox row survives and the relay sends it when it restarts. The relay is the only place duplicates come from.
Comparing the options
| Approach | Lost event | Duplicate event | Cost |
|---|---|---|---|
| Publish after commit | yes on crash | no | none |
| Publish before commit | yes (if rolled back, event still sent) | yes on retry | none |
| Outbox + relay | no | yes after relay crash | extra table, relay process |
The trade is simple: the outbox converts a lost event into a possible duplicate, and duplicates are easier to handle. The consumer stores the outbox id as a processed key in the same transaction as its own effect, so a second delivery is a no-op.
What to say when pushed
Kafka's idempotent producer does not help here, because it only deduplicates within one producer session against the broker's own log. It cannot see your Postgres commit. The outbox is needed for the database-to-broker hop, and consumer-side dedupe is needed for the duplicates it leaves behind.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-65A consumer reads from a partitioned topic, and one message fails to process on every attempt. Explain how you bound retries, when you move the message to a dead letter queue, and how you keep that one poison message from stalling the rest of its partition.
The 90-second answer
A poison message is one whose processing fails deterministically, so retrying it in place never succeeds. The consumer must therefore spend a fixed retry budget on it, then park it somewhere else and advance the offset. Without that, one bad record at offset 1,042 blocks every record behind it on that partition, because partition ordering is the reason the partition exists.
Split failures into two kinds before choosing a policy. Transient failures (timeouts, 503s, a lock held for 200 ms) deserve backoff and retry. Deterministic failures (schema mismatch, a foreign key that never resolves, a parse error) do not, and retrying them only burns budget. Classify by exception type at the handler boundary, and treat anything unclassified as transient but capped.
Retry budget and redelivery count
Keep the redelivery count in the message's headers, not in consumer memory, so a restart does not reset it. A budget of 5 attempts with exponential backoff (200 ms, 400 ms, 800 ms, 1.6 s, 3.2 s) costs about 6.2 s of blocking time on the partition in the worst case. That number matters: if your partition SLA is 2 s, blocking in place is already wrong, and you need a retry topic instead of sleeping.
Trace for one partition, budget = 5:
offset 1041 attempt 1 fail (timeout) delivery_count=1 sleep 200 ms
offset 1041 attempt 2 ok commit 1042
offset 1042 attempt 1 fail (parse) delivery_count=1 classified deterministic
-> publish to orders.dlq with headers {source_partition, source_offset, error_class, attempts}
-> commit 1043The deterministic message skipped the budget entirely. The DLQ write must succeed before the offset commit; if the DLQ publish fails, do not commit, and the partition stalls loudly, which is the correct failure.
Keeping the partition moving
Two designs, with different trade-offs:
| Approach | Partition blocked by a poison message | Ordering for the key | Operational cost |
|---|---|---|---|
| Retry in place, then DLQ | up to the full budget (about 6.2 s above) | preserved | simple, one topic |
Retry topic tiers (.retry-1m, .retry-10m), then DLQ | near zero | broken for that key: later messages overtake it | needs a replay path and dedupe |
Retry topics keep the partition flowing, but any later event for the same entity now processes before the failed one. That is acceptable for independent events and wrong for a state machine that expects created before updated. Pick by whether consumers tolerate reordering per key.
Failure modes to name
- Budget counted per consumer instance, not per message: a rebalance resets it and the message loops forever across the group. Detect with
delivery_countgrowing across rebalances. - DLQ becomes a black hole. Alert on DLQ depth and age, and make sure replay reuses the original key so ordering is restored where it matters.
- A bad deploy poisons a whole batch: thousands of messages hit the DLQ in minutes. Add a circuit: if DLQ rate exceeds a threshold (say 1% of consumed over 5 min), pause the consumer rather than dead-lettering everything.
Detection: DLQ depth and oldest-message age per topic, retries per message histogram, and consumer lag per partition. A flat lag with rising DLQ depth means the poison path is working; rising lag with flat DLQ means you are blocked somewhere and not classifying.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-66What is the main drawback of OFFSET-based pagination when rows are inserted into a table between page requests?
The 60-second answer
OFFSET numbers rows by position, not by identity. Every insert above the current offset pushes the rows below it down by one position, so the next LIMIT 50 OFFSET n request starts at a shifted place in the sort order. The client can see a row it already read again (a duplicate) or miss a row it never saw (a skip). The position it asks for and the row at that position no longer match once the table changes.
Keyset (cursor) pagination avoids this by naming the last row returned and asking for rows after it in the sort order.
-- offset: position-based, shifts under inserts and deletes
SELECT id, created_at, status FROM orders
ORDER BY created_at, id
LIMIT 50 OFFSET 100;
-- keyset: anchored to the last row returned
SELECT id, created_at, status FROM orders
WHERE (created_at, id) > (:last_created_at, :last_id)
ORDER BY created_at, id
LIMIT 50;Trade-offs and limits.
- Keyset does not repeat rows, but a row inserted with a sort key below the cursor lands in the part already read, so that traversal never returns it.
- The sort key must be unique (add
idas a tiebreaker) and indexed, or each page costs a scan and a sort. - Offset is simple and supports jumping to page 500. Its cost grows with the offset:
OFFSET 1000000reads and discards a million rows before returning anything. - Keyset cannot jump to an arbitrary page. Use it for infinite scroll, exports and sync feeds.
- A REPEATABLE READ snapshot gives a consistent view, but holding it open across user think time is a poor trade. Use it for batch jobs, not browsing.
When a client needs no duplicates and no skips while the table changes, pick keyset with a unique sort key and document that rows inserted behind the cursor are not returned.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-67Why is PUT idempotent but POST not, and how does an idempotency key make a payment retry safe? Walk me through the failure window it closes.
The 90-second answer
Idempotent means N identical requests leave the server in the same state as one. RFC 9110 classes PUT as idempotent because it replaces the target resource with the representation sent. Two identical PUT /payments/pay_7f3c calls leave one payment record. POST makes no such promise: POST /payments asks the server to create something, so each delivery can mint a new payment. A client that times out cannot tell whether the first request landed, so retrying a POST can charge the card twice.
The guarantee is about effect, not response. A second identical DELETE may return 404 and still be idempotent.
An idempotency key turns a POST into "create at most once per key". The Idempotency-Key header is an IETF draft (draft-ietf-httpapi-idempotency-key-header), not an RFC, so cite it as a draft. The server must record the key atomically with the charge, and a later request with the same key returns the stored outcome.
Trace (amount 4999 minor units, 2 s client timeout, hypothetical timings)
| t | Event | Row state |
|---|---|---|
| 0.0 s | Insert (client, k1, fingerprint, in_progress, lease_until=t+30 s), unique on (client, key) | in_progress |
| 0.3 s | Call PSP with a PSP idempotency key derived from k1; PSP charges | in_progress |
| 0.4 s | Process crashes before storing the response | in_progress |
| 2.0 s | Client times out and retries with k1 | in_progress |
| 2.0 s | Retry finds the row, lease unexpired, returns 409 with Retry-After | in_progress |
| 30.0 s | Lease expires; a retry re-calls PSP with the same derived key | in_progress |
| 30.2 s | PSP returns the original charge id; server stores response | succeeded |
The lease matters. Without it, the 2 s retry would run a second charge path concurrently with the first. Without the derived PSP key, the 30 s retry would charge again, because your own table cannot prove the PSP charge happened.
Failure modes and detection
- Fingerprint missing: a retry with a changed amount returns the old result silently. Hash the canonical body and reject a key reused with a different fingerprint (422 here, your choice; Stripe returns 400
idempotency_error). - Response stored after the PSP call instead of as a state transition: the crash window above becomes a double charge. Detect it by counting PSP charges per key against your row count.
- Key scope: keys unscoped by client let one tenant's key replay another's response.
- Retention shorter than the client's retry horizon: after expiry, the retry is a new request. Keep retention at least as long as your longest client retry budget, and check that the PSP's own window covers it too (Stripe documents a 24 h key lifetime).
The alternative: client-chosen resource id
PUT /payments/{client_generated_id} makes idempotency structural: the URL is the uniqueness key and no separate key table is needed. Repeating the same body is a no-op. A different body on an existing id must return 409 instead of overwriting. You still need the PSP call guarded by the same lease and derived key, so the PUT form moves the problem rather than removing it.
I would ship POST with a key, because payment creation has to return a server-assigned id, and I would keep the state machine explicit in the table rather than inferring it from the response.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-68A client gets 429 with Retry-After: 30 from an API. Explain how it should use that header to schedule its next attempt, and why a fixed one-second sleep is wrong.
The 90-second answer
Retry-After is the server's earliest useful retry point, so it is a floor on the wait, not a suggestion. RFC 9110 section 10.2.3 allows delay-seconds (Retry-After: 30) or an HTTP-date. For the delay form, the client waits at least 30 seconds before the next attempt for that credential. A fixed one-second sleep ignores the server's signal, so the client retries inside the window that the limiter is still enforcing, gets another 429, and burns quota on rejected calls.
The mechanism is the window. Suppose the limit is 100 requests per 60 s and the client has 200 workers. At t=0 every worker gets a 429. With a one-second sleep, each worker retries about once per second, so roughly 200 requests arrive every second. The limiter rejects them all, the header is re-issued, and the client never leaves the blocked state.
A correct design keeps one shared not_before timestamp per credential, set to now + Retry-After whenever any worker sees a 429. Every worker checks that timestamp before sending. Added jitter spreads the retries after the floor so they do not all land on the same instant.
import threading, time, random
class Gate:
def __init__(self):
self._lock = threading.Lock()
self._not_before = 0.0
def push_out(self, seconds):
with self._lock:
self._not_before = max(self._not_before, time.monotonic() + seconds)
def wait(self):
delay = self._not_before - time.monotonic()
if delay > 0:
time.sleep(delay)
gate = Gate()
gate.push_out(30 + random.uniform(0, 5)) # on a 429 with Retry-After: 30Trace: 200 workers receive the 429 at t=0. Each calls push_out(30 + jitter), and the maximum wins. All workers sleep until about t=30 and then send. Arrivals still bunch near t=30, so the jitter window should be wide enough that arrivals per second stay under the refill rate. With 200 retries spread over 20 s you get about 10 per second.
Trade-offs and failure modes
- Delay-seconds versus HTTP-date: delay-seconds avoids clock skew between client and server. Use HTTP-date only when the server sends nothing else, and log the parsed wait against the server's timestamp.
- Missing header: fall back to exponential backoff with a cap, and do not treat the absence as permission to retry immediately.
- Retries on writes: a 429 means the request was rejected, but a timeout or 503 may not be. Send writes with an
Idempotency-Keybefore retrying them. - Detection: alert on the 429-to-2xx ratio per credential. A rising ratio with flat traffic means workers are ignoring the gate.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-69Three components in series each have 99.9% availability. What availability does the path have, and how much downtime does that allow per 30-day month?
The 90-second answer
Serial components multiply. The path succeeds only when every hop succeeds, so availability is the product of the parts: 0.999 × 0.999 × 0.999 = 0.997003, about 99.70%. I would state the assumption that the failures are independent before quoting it, since correlated outages make the real figure lower.
Convert to downtime over a 30-day month of 43,200 minutes:
| Configuration | Calculation | Availability | Downtime per 30 days |
|---|---|---|---|
| One component | 0.999 | 99.900% | 43.2 min |
| Three in series | 0.999³ | 99.700% | 129.6 min |
A single 99.9% component allows 43.2 minutes a month. The three-hop path allows about three times that, because each hop contributes its own failure time. The path figure is worse than any single hop, which is the main point to make live.
Why the product and not the minimum
A tempting shortcut is to say the path is only as good as its weakest hop. That understates the loss. Each hop can fail independently, so the path fails whenever any one of them does. The probability of at least one failure is 1 − (1 − 0.001)³ ≈ 0.003, which matches the product.
Where the figure stops being accurate
The independence assumption fails when hops share a deploy pipeline, a certificate, a region or a connection pool. Shared causes make the real path availability lower than 99.70%. Name that caveat in one sentence and move on.
What to check before quoting
The 99.9% per component should come from measured success over a window, not from the target the team hopes to hit. Three hops at 99.9% already consume a large share of a 99.9% budget, so the path needs a figure to be argued against, not assumed.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-70A service handles 86,400 requests per day spread evenly over the day. What is the average QPS?
The 30-second answer
One request per second on average. There are 86,400 seconds in a day (24 × 60 × 60), so 86,400 requests spread evenly over those seconds is 86,400 / 86,400 = 1 QPS.
The rule to carry into a real estimate: average QPS = daily requests / 86,400. Keep that divisor in your head and the conversion takes one step.
Two things to say out loud. Real traffic is not flat, so the average understates the load at the busiest hour; size capacity against peak QPS, which is commonly 2 to 3 times the average, and label that factor as an assumption. Also, a 'request' here means the traffic you are counting. If you are sizing writes only, divide the write count, not total requests.
The same rule scales directly. At 2 × 10^8 requests per day, the average is 2 × 10^8 / 86,400 ≈ 2,315 QPS.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-71Your timeline service pushes each post into follower feeds on write, which works for most accounts. A celebrity with 40 million followers posts. Walk me through the write path, where you draw the push-or-pull line, and what breaks near that line.
The 90-second answer
Push on write for ordinary accounts, pull on read for celebrities, and merge the two at read time. Push gives every follower a precomputed list, so the read is one range scan. Fanning out one post to 40 million followers is 40 million writes, and that is the cost the hybrid exists to avoid. Above a follower threshold T, the author's post is not pushed at all. It is appended to the author's post log, and a reader's feed is their precomputed list merged with the recent posts of the celebrities they follow.
The question I'd ask first is what the SLO is. If the requirement is that a post appears in follower feeds within 60 s, the threshold is set by fan-out throughput, not by taste.
Arithmetic (hypothetical figures)
Assume 5 million ordinary posts per day, mean 300 followers each. That is 1.5 billion timeline inserts per day, about 17,400 per second on average, and peaks run several times that. A fan-out worker pool that sustains 50,000 inserts per second takes 40,000,000 / 50,000 = 800 s, about 13 minutes, to deliver one celebrity post by push. The last follower sees it 13 minutes late, which misses the 60 s target by a wide margin.
Now size T. In 60 s the pool completes 50,000 × 60 = 3,000,000 inserts. That is the ceiling for a single post, not the threshold. Most of that capacity is already needed for the ordinary stream. Reserve a quarter of it for any one post's burst: 0.25 × 3,000,000 = 750,000. So T = 750,000 is the largest follower count whose push fits the 60 s SLO with headroom left for other traffic. Treat that number as a starting point. Set it from measured sustained insert throughput per shard, not from this estimate.
Trace
Celebrity c_77 has 40,000,000 followers, which is above T. It publishes post 9001 at t=0. The post is appended to c_77's post log and nothing is fanned out. User u_5 follows c_77 and opens the feed at t=2 s. The read path does three things. It reads u_5's precomputed list, which holds ordinary-author posts up to 8990. It fetches c_77's recent post ids, which returns [9001]. It merges both by sequence id and returns the page. Cost: one list read plus one small read per followed celebrity, so a user following 5 celebrities pays 6 reads.
| Path | Write cost per post | Read cost per page | Staleness |
|---|---|---|---|
| Pure push | followers inserts | 1 read | fan-out lag |
| Pure pull | 1 log append | followees reads, merge | none |
| Hybrid, threshold T | followers inserts if followers ≤ T, otherwise 1 log append | 1 + celebrities followed | none for above-T authors |
Failure modes and how you detect them
Threshold flapping. An account that hovers around T can switch paths, leaving some followers with a copy and some without. Use a sticky rule: decide at post time from the follower count then, and never re-fan old posts when the author crosses T.
Hot key on the celebrity post list. 10 million readers asking for c_77's recent list at once is a single hot key. Cache it per edge for 1 to 2 s and coalesce concurrent misses into one backend call. Watch QPS per key, not only per shard.
Deletes. A pushed copy must be removed from every follower list, which is fan-out again. A pulled post needs only one delete. Keep a tombstone on the post log and filter at merge time, or the deleted post keeps showing in pushed lists.
Merge ordering. Timestamps come from different hosts. Sort by a monotonic sequence id assigned at write, not by wall clock, or two posts a few ms apart can swap order between reads.
Metrics that catch these: publish-to-last-timeline-write lag per post at p99, celebrity-list hit rate, and read p99 split by how many celebrities the reader follows.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-72A typeahead service stores 50 million phrases in a trie and must return the top 5 completions for a prefix. Compare walking the subtree at query time with storing the top 5 at each node. What does each cost per query, and what does the precomputed version cost in memory?
The 90-second answer
I'd first fix the assumptions: 5 suggestions per keystroke, phrases ranked by a static score that changes in batches, and a server-side lookup that has to be fast regardless of how short the prefix is.
Walking the trie at query time means descending L characters to reach the prefix node, then visiting every completion under it and keeping the best 5. The cost is O(L + S), where S is the number of phrases in that subtree. A one-letter prefix like a can have millions of completions, so the walk is cheap for rare prefixes and expensive for common ones.
Storing the top 5 at each node flips that. The query descends L characters and reads a list of 5 entries, O(L + 5). The price is that every phrase of length m has to be inserted into up to m nodes' lists, so the storage grows with total characters, not with phrase count alone.
Worked numbers (hypothetical)
Assume 50 M phrases averaging 18 characters and 120 M trie nodes after sharing prefixes. Each stored entry is a phrase id plus a score, 8 bytes together, and each node keeps 5 entries. That is 120 M × 5 × 8 B = 4.8 GB just for the lists, before child pointers.
| Design | Query cost | Extra memory | Update cost |
|---|---|---|---|
| Walk the subtree | O(L + S) | none | rebuild is free |
| Top 5 at every node | O(L + 5) | about 4.8 GB here | each score change rewrites lists on its path |
A common middle ground stores precomputed lists only at nodes near the root, where subtrees are largest, and walks below that depth.
Failure modes
The walk design shows up as a p99 spike on short prefixes. Detect it with latency histograms bucketed by prefix length. The precomputed design shows up as memory growth past the box limit after a bulk import, which you catch by tracking bytes per node in the build job. Rebuild lists in a new structure and swap a pointer, so readers never see a half-written list.
Choose precomputed lists when reads dominate and memory fits. Choose the walk when memory is tight and short-prefix traffic is light.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-73Your ID service issues 64-bit Snowflake-style IDs from many nodes. Walk me through the bit layout, then explain what a backward clock step on one node does to uniqueness and to ordering.
The 90-second answer
A Snowflake ID packs three fields into 64 bits: a 41-bit millisecond timestamp, a 10-bit worker id, and a 12-bit per-millisecond sequence. The top bit stays zero so the value sorts as a positive signed int64. Uniqueness comes from the tuple (timestamp, worker, sequence). Within one worker, two IDs can only collide if the clock repeats a millisecond and the sequence repeats, and the generator prevents both. Ordering is only as good as the clocks. Clock skew between workers means IDs sort by time only to within the skew bound, and a backward clock step on one node can reissue timestamps it already used.
| Field | Bits | Range | Notes |
|---|---|---|---|
| sign | 1 | 0 | keeps the value non-negative |
| timestamp | 41 | ms since custom epoch | about 69.7 years of range |
| worker id | 10 | 0 to 1023 | assigned at startup |
| sequence | 12 | 0 to 4095 | IDs per worker per ms |
Per worker the ceiling is 4,096 IDs per millisecond, about 4.1 million per second. Across 1,024 workers the theoretical fleet ceiling is about 4.2 billion per second, far above what a single shared counter could serve.
Generation loop
def next_id(self):
now = now_ms()
if now < self.last_ts:
# clock went backwards: stall rather than reuse a timestamp
if self.last_ts - now > self.max_stall_ms:
raise ClockSkewError(self.last_ts - now)
sleep_ms(self.last_ts - now)
now = now_ms()
if now == self.last_ts:
self.seq = (self.seq + 1) & 0xFFF
if self.seq == 0:
now = wait_until_next_ms(self.last_ts)
else:
self.seq = 0
self.last_ts = now
return ((now - EPOCH) << 22) | (self.worker << 12) | self.seqTrace. Worker 5 is at timestamp 1000 ms and has issued sequences 0 to 4095, so the next call waits for 1001 ms and continues from sequence 0. Later NTP steps the clock back 2 ms to 998. Without the guard, the node would emit (998, 5, 0), which duplicates an ID it already issued at 998 ms. With the guard it sleeps 2 ms, which is observable and bounded.
Ordering across nodes. Two workers whose clocks differ by d ms can produce IDs whose sort order contradicts causal order when the events are closer than d. If the event on node A happens 3 ms after an event on node B, but A's clock runs 5 ms behind, A's ID sorts first. So the guarantee is roughly monotone per worker and approximately ordered globally. Anything that needs a strict happens-before order needs a logical clock or a single sequencer, not Snowflake IDs.
Alternatives. A central sequence (database sequence or a ticket server) gives strict order and a single point of failure and a throughput cap. UUIDv7 keeps the time prefix but spends 74 random bits, which removes the worker-id assignment problem at the cost of width and no sequence guarantee within a millisecond.
Failure modes to name. Worker id collisions after a redeploy, detected by a lease in a coordination store. Clock steps larger than the stall budget, detected by a counter on ClockSkewError. Sequence exhaustion under bursts, visible as latency spikes of up to 1 ms per burst.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-74In content-defined chunking for a file sync service, what decides where one chunk ends and the next begins?
The 60-second answer
The content does. A rolling hash, typically a Rabin fingerprint over a sliding window of about 48 bytes, is updated one byte at a time as the scanner moves through the file. Whenever the low bits of that fingerprint are all zero, the scanner declares a chunk boundary. With a 13-bit mask the boundary probability is 1 in 8,192 per position, which gives an average chunk near 8 KB.
The boundary test depends only on the bytes inside the window, not on the byte offset from the start of the file. That is the property that matters: an edit changes the fingerprints only for the windows that overlap it, so boundaries far from the edit stay where they were.
Min and max bounds
The raw mask alone can produce chunks of a few bytes or a single enormous chunk. Production systems enforce a minimum (for example 2 KB) that skips any boundary inside it, and a maximum (for example 64 KB) that forces a cut. Both are part of the chunking rule, not afterthoughts.
Chunk identity is separate
The rolling fingerprint only chooses cut points. Each chunk is then named by a cryptographic hash of its bytes, usually SHA-256, and that hash is what the store deduplicates on. A 32-bit fingerprint collision therefore cannot merge two different chunks.
Failure modes
- Content with no matching windows (a long run of zeros, for example) hits the maximum and produces fixed-size cuts there, so dedup benefit disappears in that region.
- Encrypting each device's copy with a random key makes identical plaintext produce different ciphertext, so chunks never match. Chunking must happen on plaintext or use convergent encryption, with the privacy cost that brings.
When not to use it
Append-only files such as logs always change at the end, so fixed-size chunks give the same result at lower CPU cost.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-75A leader holds a 10-second lease, then stalls for 15 seconds in a garbage collection pause. A second node takes over. How do you stop the stalled leader's writes from corrupting the data, and what must the storage layer check?
The 90-second answer
A lease tells the holder when it may act. It cannot stop a holder that is paused, because the holder's view of time stops with it. So the storage layer has to enforce the decision with a fencing token: a number from the coordination service that increases on every grant, which the resource compares on every write. Assumptions: the coordinator (etcd or ZooKeeper) hands out a monotonic revision with each lease grant, and the resource is a store I control, so I can make the token check and the write one atomic step.
Trace, with a 10 s TTL:
- t=0: A acquires the lease with token 33 and renews every 3 s.
- t=4: A enters a 15 s stop-the-world pause. It stops renewing.
- t=10: the lease expires. B acquires it with token 34 and writes. The store records max_token=34.
- t=19: A wakes up. Its local belief that it is still leader is stale, so it issues a write carrying token 33.
- The store sees 33 < 34 and rejects the write with 409 fenced. Nothing is applied.
The check has to live inside the commit:
BEGIN;
UPDATE fence SET max_token = :token
WHERE resource = 'orders' AND max_token <= :token
RETURNING max_token;
-- zero rows returned: ROLLBACK and report fenced
UPDATE orders SET status = :status WHERE id = :id;
COMMIT;A client-side check such as "lease still valid at t=18.9" does not work. The holder can pass that check and then pause before the write. Any check separated from the write in time can be overtaken.
Lease length is about liveness, not safety. The TTL must exceed normal renewal jitter, or leadership flaps. If it is shorter than the pause, the cost is a window where B leads and A is still running but fenced. Writes stay correct, but A may do wasted work. Clock skew does not extend A's lease, because the coordinator measures the lease, not the holder. A's own "am I leader" check should use a local monotonic deadline minus a margin, and treat the result as advisory only.
Consensus systems get this for free. In Raft, the term number serves as the fencing token. A deposed leader cannot commit, because its appends never reach a quorum. The gap is reads: a stale leader still answers reads unless reads use ReadIndex or check the term against a quorum.
Failure modes and detection:
- Unfenced storage: silent corruption, found only by audit or reconciliation diffs. Detect it in design review, not in production.
- Non-monotonic tokens, such as wall-clock timestamps: the old leader can win. Assert strictly increasing tokens on every grant, and alert on any decrease.
- External APIs with no token support: use a version precondition (If-Match or a conditional update) as the fence. With no precondition at all, you cannot be safe against pauses, and you should say so out loud.
Watch fenced_writes_total and leader changes per hour. Rising fenced writes mean pauses are happening in production, and that usually points at GC tuning or a noisy neighbour, not at the lock service.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-76With writes acknowledged by 2 of 3 regions, what sets the latency of a quorum write, and when would you pin writes to one home region instead?
The 90-second answer
A quorum write finishes when the coordinator holds acknowledgements from enough replicas to form a majority. With 3 regions and a quorum of 2, the coordinator's own copy is one vote, so the write waits for the nearest remote replica that completes the majority. Write latency is therefore set by the round trip to that one replica, not by the slowest region.
The quorum adds one cross-region round trip whenever the coordinator is local to the client. It adds two whenever the client is routed to a coordinator far from itself, because the client pays a trip to the coordinator and the coordinator pays a trip for the quorum. That second trip is the usual cause of a number like 180 ms, so I would check coordinator placement before blaming the consistency model.
Trace (hypothetical RTTs, labelled as such). Frankfurt to Frankfurt is about 1 ms. Frankfurt to us-east-1 is about 90 ms. Frankfurt to ap-southeast-1 is about 160 ms.
| Path | Latency | Notes |
|---|---|---|
| Local coordinator, quorum via us-east-1 | 1 ms + 90 ms ≈ 91 ms | one cross-region hop |
| Remote coordinator in us-east-1, quorum via Frankfurt | 90 ms + 90 ms = 180 ms | misrouted, two hops |
| Single home region in Frankfurt | 1 ms | no cross-region ack on the write path |
Single home region versus quorum. Pinning writes to one region removes the quorum wait and removes concurrent writes to the same key from two places, so conflict handling disappears. The cost is that writes from far away pay the full RTT on every call, and losing the home region stops writes until a failover completes. Quorum across regions keeps writes available through one region's loss and keeps write latency bounded by the nearest peer, but it puts a cross-region round trip on every write and needs a conflict or ordering rule for overlapping writers.
Failure modes. With a single home region and asynchronous replication, a failover can lose acknowledged writes, so the new leader must be fenced: use a lease with a fencing token and promote only a replica that has the last committed log position. With quorum writes, a slow but not dead region raises quorum latency for every client whose nearest peer it is. Track the second-fastest ack per coordinator and alert when it exceeds the write budget.
Pick. For an order-status service whose writes come mostly from one country, I would pin writes to a home region with a synchronous standby nearby and accept a slower failover. For a profile store written from several continents, I would use quorum across three regions and route each client to its nearest coordinator.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-77A downstream pricing call that normally takes 40 ms now takes 4 s for most requests. Explain what a circuit breaker does with that dependency: when it opens, what the open and half-open states do, and why a slow call should count as a failure.
The 90-second answer
I treat a call that exceeds its timeout as a failure, because a slow dependency consumes threads just like a failing one. The breaker watches recent outcomes. When the failure rate crosses a threshold, it opens and rejects calls immediately without touching the dependency. After a wait, it goes half-open and lets a few probe calls through. If they succeed, it closes. If one fails, it reopens. The goal is to stop my worker threads from queuing behind a dependency that cannot answer in time.
Why slow is the real failure. Assume 200 worker threads and a per-call timeout of 500 ms (hypothetical). At 40 ms per call, the pool can sustain about 5,000 calls per second. At 4 s per call it manages about 50, and requests queue until the checkout timeout fires, including requests that never needed pricing.
| State | Call behaviour | Exit condition |
|---|---|---|
| CLOSED | calls pass through, outcomes recorded | failure-or-slow rate over threshold |
| OPEN | calls fail fast, no network I/O | wait duration elapsed |
| HALF_OPEN | a fixed number of probes allowed, the rest rejected | probes succeed to close; a failure reopens |
Worked trace (hypothetical figures). The window holds the last 100 calls. Calls 1 to 40 succeed in 40 ms. From call 41 on, calls take 4 s, time out at 500 ms, and count as failures. By call 100, 60 of 100 are failures, above a 50% threshold, so the breaker opens. Calls after that return a fast error in about 1 ms, and blocked threads drop back to near zero. After a 30 s wait the breaker admits 5 probes. If they return in 45 ms, it closes and clears the window. If one takes 4 s, it reopens and the wait starts again.
Choosing the settings. A count window is steady at high traffic and noisy at low traffic, so a time window is often a better fit for a service whose load swings. The threshold should sit above the normal error baseline, not at zero, and a minimum call count keeps one slow call at low traffic from tripping the breaker. Resilience4j's defaults are a 50% failure-rate threshold over a 100-call count window with a 60 s open wait, but confirm against your version's documentation before quoting them.
Failure modes I watch for.
- Probe stampede: if half-open admits every waiting thread, the same load hits the dependency and the breaker reopens. Cap the probe count.
- Hidden fallback load: when open, traffic goes to a fallback such as a cached price. If that path is slow too, the problem has only moved.
- Per-instance state: each of 40 instances learns separately, so the fleet recovers in slower, uncoordinated steps. Usually acceptable, but say so.
Detection: alert on state-transition counts, rejected-call rate while open, and the slow-call rate. A breaker that opens and never closes means the dependency is still down, and the rejected-call metric shows how much traffic the fallback is carrying.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-78What is the main purpose of adding random jitter to an exponential backoff schedule for retries?
The 90-second answer
Jitter spreads retries out in time. Plain exponential backoff gives every client that failed at the same moment the same sleep sequence, so they keep retrying together at 1 s, 2 s, 4 s and so on. Adding a random component to each sleep scatters those retries across the window, so the server sees a smaller spike at each retry point.
The usual form is full jitter, described in the AWS Architecture Blog post 'Exponential Backoff and Jitter' (2015): each sleep is drawn uniformly from [0, min(cap, base × 2^n)]. Jitter changes when the retries arrive, not how many there are. Ten thousand clients still make ten thousand attempts per round, so a retry budget and an attempt limit are still needed.
Worked example (hypothetical figures): 10,000 clients, base 1 s, cap 30 s, the service stays down. Attempt 0 happens at t = 1 s for everyone without jitter, which is 10,000 requests in one millisecond. With full jitter on attempt 0, the sleep is uniform on [0, 1 s], so the mean is 10 requests per millisecond, with a peak near 20.
import random
def backoff_s(n, base=1.0, cap=30.0):
return random.uniform(0, min(cap, base * 2 ** n))Failure modes and how to detect them.
- Retries multiply across layers. Three layers each retrying three times turn one failure into 27 calls at the bottom. Detect it by comparing downstream call rate with upstream request rate during an incident.
- No cap or attempt limit. Sleeps grow past the caller's deadline and hold resources for minutes. Detect it through p99 latency and in-flight counts.
- Retrying non-idempotent operations. A timed-out POST may have succeeded. Send an idempotency key or do not retry.
- Ignoring Retry-After. A 429 or 503 with Retry-After should set the floor for the next sleep.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-79A request enters a five-service chain with a 2 s client deadline. Each hop does a retry on timeout. Walk me through how the remaining deadline should shrink at each hop, and what each hop should do when its share is spent.
The 90-second answer
Propagate an absolute deadline, not a relative timeout. The edge sets deadline = now + 2000 ms and every hop forwards that absolute instant (gRPC carries it as grpc-timeout, HTTP services usually as a header like x-deadline in epoch ms). Each hop computes remaining = deadline - now() at the moment it sends, and never adds its own fixed timeout on top. The budget shrinks by the time already spent plus the hop's own processing, and it never grows.
Two things break this in production: retries that multiply load while the budget is nearly gone, and clock skew between hosts that makes a deadline appear already expired or several hundred ms too generous.
Trace (hypothetical figures, 5 hops, 2000 ms budget)
| Hop | Arrives with remaining | Local work | Calls downstream with | Notes |
|---|---|---|---|---|
| Edge | 2000 ms | 10 ms | 1990 ms | sets the deadline |
| A | 1990 ms | 15 ms | 1975 ms | |
| B | 1975 ms | 20 ms | 1955 ms | first attempt times out at 400 ms, retry gets 1535 ms |
| C | 1535 ms | 30 ms | 1505 ms | |
| D | 1505 ms | 40 ms | 1465 ms | |
| E | 1465 ms | 25 ms | leaf | no further calls |
Each hop subtracts its own elapsed time before forwarding. A retry is not a fresh 400 ms: it is whatever is left after the failed attempt, and the per-attempt timeout is min(configured attempt timeout, remaining - reserve).
What each hop does
- If
remaining <= 0on arrival, fail fast with a deadline-exceeded status (gRPCDEADLINE_EXCEEDED, HTTP 504). Do not start work the caller has already abandoned. - Reserve a slice for your own response path, for example 10 to 20 ms, so you can still serialise and return an error instead of dying silently at the edge.
- Retry only if
remainingcovers the backoff plus a full attempt, and only for idempotent operations or ones carrying an idempotency key. A retry that cannot finish is pure load. - Cap the number of attempts per hop and never retry at every hop at once. With 3 attempts at each of 5 hops, one failing leaf sees up to 3^5 = 243 calls per user request. Retry at one layer, usually the one closest to the failure, and let the rest fail fast.
- When a hop cancels a downstream call, propagate the cancellation so the callee stops work (
contextcancellation in Go,CancellationTokenin .NET, or the gRPC cancel frame). Otherwise the leaf keeps computing for a caller that left 800 ms ago.
Clock skew. Absolute deadlines assume the hosts agree on time. With NTP typically within a few ms in a healthy fleet but tens of ms or worse during faults, a hop whose clock runs 150 ms fast will drop requests that still had budget. Options: send remaining time as a duration and let each hop start its own clock on receipt (accepts the transit time as unaccounted), or keep absolute deadlines and set an explicit skew allowance in the reserve. I would ship the duration form across process boundaries because it is immune to skew, and accept a small under-count of network transit, which I bound with a per-hop reserve.
Failure modes and detection
- Retry amplification: watch the ratio of attempts to original requests per hop. Above roughly 1.1 sustained outside an incident means retries are doing damage.
- Deadlines dropped at zero remaining: count
DEADLINE_EXCEEDEDby hop. A spike at the leaf with flat upstream latency means the budget is being consumed by queueing, not by work. - Work after abandonment: compare server-side handler time for cancelled requests with the caller's elapsed time. If handlers finish long after cancel, cancellation is not reaching them.
When not to propagate deadlines: fire-and-forget work, or a background job whose result has no caller waiting. Give it its own timeout rather than inheriting a request budget that will expire before it starts.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-80A hot key gets 2,000 reads per second across 40 app instances. Explain how an in-process cache with a short TTL and a suffixed-key split each spread that load, and name the consistency each one gives up.
The 60-second answer
Both spread a hot key's load, but they do it in different places. A local in-process cache keeps a copy in every instance, so most reads never reach the shared store. Key splitting writes N copies, product:123#0 through product:123#7, and each read picks one, so the load lands on several partitions. The first costs staleness. The second costs write amplification and a window where copies disagree.
Assumptions for the numbers below (hypothetical): 2,000 reads/s, 40 instances, a 1 s TTL, N = 8.
Local cache. Each instance misses once per TTL, so the store sees about 40 reads/s instead of 2,000. The staleness bound is the TTL: after a write, an instance can serve the old value for up to 1 s. Instances also disagree with each other. A client that hits an instance refreshed 50 ms ago and then one still holding a value 900 ms old sees the value move backwards. That breaks monotonic reads, and a short TTL does not remove it, only shrinks the window.
Key splitting. Each read goes to one of 8 copies chosen at random, so each copy sees about 250 reads/s. One logical write becomes 8 puts with no transaction across them. If each put takes 3 ms and they run in sequence, readers can see a mix of old and new copies for about 24 ms. A failed put leaves some copies behind for longer, so the writer has to retry until all 8 acknowledge, or each value carries a version number and readers keep the highest.
| Local in-process cache (TTL 1 s) | Key splitting (N = 8) | |
|---|---|---|
| Reads reaching the store | about 40/s | about 250/s per copy |
| Staleness after a write | up to 1 s | about 24 ms of mixed versions |
| Monotonic reads | can go backwards between instances | can go backwards during a write |
| Writes | 1 write | 8 writes |
| Failure mode | simultaneous expiry sends 40 misses at once | a failed put leaves copies at different versions |
I'd use the local cache for a read-mostly value that can be a second stale and is rarely written. I'd use splitting when the value is written often, or when a 1 s lag is not acceptable. A local cache cannot absorb writes, so a hot counter or write-heavy row needs splitting. For a read-heavy page, I'd combine them: a short local TTL for most reads, and splitting only for the keys that still exceed one partition.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-81A 1000 by 1000 grid has walls. A robot may break at most 3 walls on its way from the top-left to the bottom-right corner, and each step, including the step that breaks a wall, takes one second. What is the minimum time, and why does Dijkstra add nothing over BFS here?
The 90-second answer
Treat the problem as shortest path on a larger graph. A state is (row, col, walls_broken), with walls_broken from 0 to 3. Stepping onto an open cell keeps the count. Stepping onto a wall is allowed only when the count is below 3, and it moves to count + 1. Every move still costs one second, so every edge in the state graph has weight 1. BFS from (0, 0, 0) gives the first time any (R-1, C-1, k) is popped. Dijkstra would order the same entries by the same key, because the key only grows by 1 per edge.
The mechanism that matters is that breaking a wall costs time only by being a step. Nothing in the cost depends on which wall you break. If breaking a wall cost 5 seconds, the edge weights would become 1 and 5, greedy settling would still need a heap, and the answer would change.
from collections import deque
def min_time(grid, K):
R, C = len(grid), len(grid[0])
dist = [[[-1] * (K + 1) for _ in range(C)] for _ in range(R)]
dist[0][0][0] = 0
q = deque([(0, 0, 0)])
while q:
r, c, k = q.popleft()
d = dist[r][c][k]
if (r, c) == (R - 1, C - 1):
return d
for dr, dc in ((1, 0), (-1, 0), (0, 1), (0, -1)):
nr, nc = r + dr, c + dc
if 0 <= nr < R and 0 <= nc < C:
nk = k + (grid[nr][nc] == '#')
if nk <= K and dist[nr][nc][nk] < 0:
dist[nr][nc][nk] = d + 1
q.append((nr, nc, nk))
return -1The first time the target is popped, its distance is minimal, because the queue is in nondecreasing distance order. The check on the target can return early, and it does not need to wait for the queue to empty.
Why the visited key includes the wall count
Marking visited on (row, col) alone is a real bug. A path that reaches a cell with two walls broken can be faster to that cell and still be worse later, because it has less budget to pass the next wall. Keep the count in the key. You can prune a state that is dominated, meaning the same cell was reached at no later time with no more breaks used, but the plain version above is already correct.
Cost
The state space has R × C × (K + 1) = 4 × 10^6 states, each with four neighbour checks. Time is O(RC·K), and memory is about 4 million ints for the distance table. With K fixed at 3, that is linear in the grid size.
Trace on a 2 × 3 grid, K = 1 (# = wall)
S . #
# # .From (0,0,0), the open neighbour (0,1) is at time 1. Reaching (0,2) needs the wall, so (0,2,1) is at time 2. Its neighbour (1,2) is open, giving the target (1,2,1) at time 3. Without the budget the answer would not exist, so the search returns -1 if K = 0.
Failure modes to test
Forgetting to clamp nk <= K lets the search break unlimited walls. Keying visited on the cell alone gives answers that are too large on the test where a shorter route needs a later wall break. Returning 0 instead of -1 when the target is cut off by walls is the easiest mistake to miss.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-82Which property of a binary max-heap lets you read the largest score in O(1) time, and why does that property not give you a player's rank?
The 30-second answer
The heap property says every parent is at least as large as its children. That makes the root the maximum, so the top score is one array read, heap[0], and the cost is O(1).
The same property does not give a rank. It orders each parent above its children, but it says nothing about how a node compares to nodes in other branches. Two siblings can sit in any order, so a player's rank depends on how many scores exceed theirs across the whole structure.
What to say next. For rank queries on a changing leaderboard, use a balanced tree with subtree sizes, or a skip list with span counts. Each node stores the size of its subtree, so the rank of a key comes from one root-to-node walk in O(log n). A heap would have to visit every larger score to count them.
Costs.
- Heap top-1: O(1). Heap insert: O(log n).
- Heap rank: O(rank), since every larger score must be counted.
- Augmented tree rank, insert and delete: O(log n) each.
A good follow-up is the composite key. Scores tie, so store (score, player_id) as the key to keep every node unique and the rank deterministic.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-83Describe a production incident you owned from detection to close. Which numbers showed the impact, and which number did you almost get wrong?
The 90-second answer
Name the incident and your role first: primary on-call and incident commander for a 47-minute partial outage of checkout, caused by a config change to a payment-service connection pool. Then give the outcome in numbers before the narrative, because the follow-up will be about the data. The figures below are illustrative; use your own rollup.
| Window | Checkout rpm | 5xx on /checkout | p99 latency |
|---|---|---|---|
| 14:00 to 14:20, before | 4,800 | 0.2% | 420 ms |
| 14:20 to 15:07, incident | 4,700 | 11.8% | 6.1 s |
| 15:07 to 15:30, after rollback | 4,900 | 0.3% | 450 ms |
Arithmetic for the impact: 11.8% of 4,700 requests a minute over 47 minutes is about 26,000 failed checkouts. I reported that as a range, not a single number, because client retries recovered some of them. The retry-success ratio in the logs gave a recovery band of 35 to 45%, so I quoted 14,000 to 17,000 lost orders and said how I got there.
Mechanism. The config change cut the pool for the fraud-check client from 100 connections to 20. Before the change the fraud check took about 40 ms, so 20 connections could serve 20 / 0.04 = 500 calls a second, well above the 80 a second arriving. A dependency slowdown pushed the fraud check to about 900 ms. Throughput for 20 connections fell to 20 / 0.9, about 22 a second. Queue wait grew without bound until acquire waits passed the 1 s upstream timeout, and then every request in the queue failed. Client retries multiplied the load on the same saturated pool, which is why the error rate kept climbing after the dependency partly recovered.
The decision I owned. Rollback was faster than a fix-forward because the pool size was the only change in the deploy. The config lived in a separate pipeline, so the rollback took 12 minutes, not the 2 I had estimated. I said that on the bridge so nobody waited for a second rollback.
The number I almost got wrong. The dashboard showed p99 averaged across hosts, which hid the problem: two of 24 hosts carried almost all the timeouts. I checked per-host p99 before paging the dependency team. Averaging would have sent us to the fraud service for an hour.
What changed afterward. Alert on connection-pool acquire wait, not only on error rate, because the acquire wait rose three minutes before errors did. Load-test pool changes at 1.5 times peak. Put retry budgets on the client so retries cannot exceed 10% of normal traffic. The config pipeline now runs the same canary as code. The next pool change went to 5% of traffic first and was caught at the 5% gate.
What the interviewer is testing. Whether you can state the impact with a defensible range, explain the mechanism with arithmetic, and name the mistake in your own process.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-84Tell me about a technical decision you argued against, lost, and then carried out fully. What was your objection, and what did you do once the team chose the other option?
The 90-second answer
I'd name the decision, the specific failure I predicted, and what I did after the team went the other way. The point is that I committed to the chosen design and still watched the risk I had raised.
The decision was how our order API deduplicated retried POST /orders calls. The team chose an in-process map in each pod, keyed by Idempotency-Key, with a 10-minute expiry. I argued for a unique constraint on (merchant_id, idempotency_key) in the same database transaction as the order insert.
The objection. A per-pod map only protects a retry that lands on the same pod. We run 6 pods behind a load balancer that spreads requests round-robin. A client that times out and retries has a 5 in 6 chance of hitting a different pod, and that pod has never seen the key. Hypothetical figures: with 1,000 retries a day, about 830 would miss the map and create a second order.
| Option | Retry lands on same pod | Retry lands on other pod |
|---|---|---|
| Per-pod map | Deduplicated | Duplicate order created |
| Unique constraint in the order transaction | Rejected with 409 | Rejected with 409 |
I put this table and the 5-in-6 arithmetic in the design review and asked for it to be recorded. Then I accepted that the team had decided.
Committing. I built the per-pod map as specified and did not sabotage it or leave it half-done. I added a counter for POST requests that reuse a key already seen by another pod, which I could only detect through the order ID collision check at insert. I also wrote the expiry test so the map behaved exactly as the spec said.
Reopening. Before launch we agreed one trigger: if the duplicate counter shows any real duplicate orders in a week, the decision goes back to review. In week three it showed 14. I wrote that up with the counts, and the team moved the constraint into the order transaction the following sprint.
What I'd say about the outcome: I was right, and it cost us 14 duplicate orders and a few refunds. Committing still made sense, because the risk was visible and the reopen rule was set before anyone had to argue about it.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-85Your release is due Friday and one validation check cannot finish before then. Compare shipping behind a 5% flag with holding the release, and say which fact about the failure mode decides it?
The 90-second answer
Start by naming the unknown precisely. Here it is the failure mode: does the change double-post under retry, and at what rate? Staging does not reproduce production retry storms, so the duplicate rate is a hypothesis until measured. With a fixed Friday deadline, waiting for the full check is one option on the table, and I would compare it honestly against the flag rather than assume the flag wins.
The decision turns on blast radius and reversibility, not on confidence in the code. A flag limits exposure to the slice you route. The question then becomes whether a bad outcome inside that slice can be undone cheaply.
Hypothetical figures, labelled as such: the ledger path handles 2 million messages a day. At 5% routing, 100,000 messages a day take the new path.
| Ship behind 5% flag | Hold release | |
|---|---|---|
| Exposure | 5% of traffic, removed by flag flip | none |
| Duplicates at 0.01% under retry | 10 a day, found within hours | none |
| Duplicates at 1% under retry | 1,000 a day, reversal cost dominates | none |
| Cost | reversal work on bad postings | missed deadline, old path stays |
At 0.01% I ship. At 1% I hold, because the reversal work for 1,000 postings a day outweighs the deadline. The threshold for each case is set before the rollout, so the numbers cannot be reinterpreted after they arrive.
The mechanism that makes the flag safe
The flag bounds damage only if duplicates fail at write, not at read. Enforce the idempotency key with a unique constraint in the database, so a replayed message is rejected by the insert. A consumer-side check alone races under concurrent redelivery, and the flag then limits nothing.
Failure modes to name
Detection lag is the one that bites. A duplicate check that runs hourly lets roughly 1,000 duplicates post before anyone sees them at the 1% rate. Name the detector and its latency.
Rollback is also a risk. If turning the flag off replays in-flight messages through the old path, the rollback itself can duplicate. Check that the old path can drain cleanly before you rely on it as the escape.
The fact that decides it is this: the failure is detectable within hours and reversible with a constraint in place, at a rate the slice can absorb. If any of those three fails, holding is the correct answer, however late it makes the release.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-86When you trade roadmap time for a customer fix, which measure do you agree on before you build, and why?
The 60-second answer
Agree on the outcome the customer feels, written as a number you can measure after launch. Not the thing you built, and not the thing that is easy to count. For a fix that moves work out of a synchronous request, that is usually the time from the customer's action to the point where their result is final.
The rule is simple: the success metric has to be something the customer would notice if it went wrong. Request counts, 202 responses and deploy dates are all things the team controls, so they can look good while the customer still waits.
Worked example (hypothetical figures). Checkout times out on tax calculation at peak. The fix accepts the order immediately and computes tax in a worker. Two numbers look like wins:
| Metric | Before | After |
|---|---|---|
| Submit 5xx rate | 1.8% | 0.1% |
| p99 submit latency | 3.4 s | 620 ms |
| Time from submit to final total | 1.2 s | 48 s at p95 |
The first two rows are true and the third is the customer's experience. A reviewer who only sees the first two would sign off on a change that leaves some orders stuck for close to a minute. So the agreed measure is time to final total, with a target such as p95 under 5 s, and the submit metrics are secondary.
Why agree it before building. Once the work is done, people pick the metric that shows the work well. Agreeing on it first also tells you what the roadmap trade is worth. If the customer outcome barely moves, the five engineer-weeks were spent on a number nobody felt.
What to say in the room. Name the measure, its current value, its target, and who else can see the same dashboard. Then say what you would stop doing if it did not move.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-87Walk me through how you traced a regression to its cause using metrics and logs. Which signals did you look at first, how did you narrow the change window, and how did you confirm the root cause rather than a correlated deploy?
The 90-second answer
I start with the metric that the customer felt, not the one a dashboard default shows. For a latency regression that means p99 per endpoint, split by region and by build version, over a window long enough to cover the deploy and at least one traffic peak. The first question is whether the regression is a step (one deploy, one time) or a slope (a leak, a growing queue, a cache filling up). A step points at a change. A slope points at a resource.
Then I narrow the change window by lining up three series on the same time axis: the deploy and config-change timeline, the error rate, and the latency. I am looking for the first minute the curve bends. If it bends within a minute of a rollout to some hosts and not others, the canary split is the strongest evidence I can get, because it holds time and traffic mix constant and varies only the build.
Logs come next, but only after I have a candidate. I do not grep for errors in general. I filter to the slow requests and compare a fixed field set between good and bad hosts: downstream call name, cache hit or miss, payload size bucket, tenant. A regression that appears only for one downstream call is a different story from one spread evenly across calls.
Confirming it is the cause, not a neighbour
A correlated deploy is the usual trap. Two changes shipped in the same hour, and the one I suspected is innocent. Three checks separate them:
- Revert or flag off the suspect change alone, on a subset of hosts, and watch the same metric recover within one scrape interval.
- Check the mechanism, not only the timing. If I think a new serializer is slow, the span for serialization should have grown by roughly the size of the regression. Trace arithmetic: p99 went from 40 ms to 180 ms, so the added 140 ms must appear as a span or as a counter, or the hypothesis is wrong.
- Look for the control group. Hosts running the old build during the same window should show a flat line.
window: 14:02 deploy 2026.11.18-3 begins (canary 10%)
14:03 canary p99 41 ms -> 176 ms control p99 40 ms -> 41 ms
14:03 span serialize.encode 2 ms -> 131 ms (canary only)
14:09 flag new_encoder=off on canary -> p99 43 ms within 1 scrapeIf the span moves by the same amount as the metric, and the flag closes the gap, I have a causal chain I can defend. If the flag does not close it, I keep looking, and I say so.
Where this goes wrong
- Averages hide it. A mean that moved 5 ms can hide a p99 that moved 140 ms, so I always check tail percentiles and the histogram shape.
- Sampling bias. If tracing samples 1% of requests, a rare slow path may not appear in the trace store at all. I count requests by path in the metrics first.
- Log volume and clock skew. Log timestamps from different hosts can disagree by hundreds of milliseconds. I order events with the request id, not wall-clock alone.
- Cardinality explosions. Adding a high-cardinality label to find the bug can itself be the regression. I check the metrics pipeline cost before I trust its new labels.
What I say at the end matters as much as the trace: what I confirmed directly, what I inferred, and what would change my mind.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-88You shipped a change that another team depends on. You now suspect it is wrong, but you have no root cause yet. Compare telling them immediately with waiting for the root cause. What is the main trade-off?
The 90-second answer
I would tell them as soon as I have a credible suspicion and a bounded impact estimate, and I would say plainly that the root cause is still open. Waiting for the root cause protects the wording of the message. Disclosing early protects the dependents' decisions, and those decisions are what the bad change is actually affecting. The main trade-off is accuracy of the signal against the time it spends unseen. Early disclosure gives you a provisional, sometimes wrong number. Late disclosure gives you a correct number after the damage has already been done.
Why the trade-off exists
Dependents act on your signal. They pause a job, retry a request, or reconcile a table. Each of those actions is cheap to start and expensive to undo, and the cost of silence is roughly the affected rate times the hours until someone downstream knows. Suppose a change makes 3 consumers each retry failed orders on a 6-hour backoff. Your team is paying for every hour the consumers still believe the data is fine.
Two approaches, compared
| Disclose early (suspicion plus bound) | Wait for root cause | |
|---|---|---|
| What dependents get | A provisional count, window, and a request to pause | One accurate message, later |
| Exposure window | Minutes to contain | Until root cause, possibly days |
| Main risk | Figure is wrong and must be corrected | Damage keeps accumulating |
| Credibility cost | A visible correction | A late discovery that looks like concealment |
| Use when | Dependents act automatically or the impact grows | Impact is contained and nobody downstream acts on it |
Failure mode that catches early disclosers
The count is usually undercounted at first. In a hypothetical run, my first query found 310 duplicate orders, but it only checked keys younger than the 1-hour window. The 6-hour retries arrived after expiry and were missed. The count reached 1,240 on day 3. Two things prevent this. State the query and the window with the number, so readers can check it. And count by the age of the retry, not only by recent keys.
Detection
This kind of error shows up in reconciliation, not in the service's own alerts, because the service still returns success. A reconciliation job that compares orders against an external ledger is the signal to watch, along with a count of retries whose key has already expired.
Answer to the trade-off question
Early disclosure wins whenever dependents can act on the signal and the impact is still growing. Waiting only makes sense when the impact is fixed and nobody downstream acts on it. Either way, the message should carry its method and its confidence level, so the first number can be corrected without reopening the trust question.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-89Tell me about a project where you delivered a measurable result. What was the metric before and after, and what share of the change came from your work?
The 90-second answer
I pick a project where the metric existed before I started and still exists. I name it exactly: p99 latency of GET /checkout measured at the load balancer over seven days, not "checkout got faster". Then I give the baseline, the after value, and the window I used for each, because a before number from a bad week flatters any change.
Then I split the total change between the people who shipped it. That split is the part interviewers push on, and it's where most candidates overclaim.
Example, with hypothetical figures:
| Item | Value |
|---|---|
| p99 baseline, 7 days before launch | 1,800 ms |
| p99 after, 7 days after launch | 620 ms |
| Total change | -1,180 ms (-66%) |
| Pricing-lookup cache (my change) | -700 ms |
| Connection pool resize (another engineer) | -300 ms |
| Bot-traffic filter (third team) | -180 ms |
My share is 700 / 1,180, about 59%. I say it as "roughly 60% of the improvement, and the cache was my design and my rollout", not "I cut latency by 66%".
How I got the attribution
A before and after comparison alone is weak here, because traffic mix shifted during the window. I ran the cache behind a flag at 10% of hosts for two days, so the canary and control saw the same hour-of-day and the same request mix. The 700 ms came from that comparison, not from subtracting one week from another. The pool resize and bot filter were measured by their owners the same way, and the three numbers sum to the observed total, which is the check I used to know I wasn't double-counting.
What I'd say about the parts I didn't own
I describe the other changes in one clause each and move on. Listing them shows I know the system, and it stops the answer reading as a solo heroics story. If the interviewer asks what I would have done alone, I answer with the mechanism: the cache alone would have cut p99 to roughly 1,100 ms, because the pool was saturating at 20 connections during peak and cache misses still queued behind it.
Failure modes I watch for
- The metric moved for a reason unrelated to the change, such as a traffic dip or a dependency's own fix. The control group catches this.
- The metric improved but a guardrail regressed, such as error rate or stale prices. I name the guardrail and its number too.
- The number is an average or a p50 presented as p99. I state the percentile every time.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-90Under the Frugality leadership principle, what is the first number you would check before proposing a cost reduction, and why?
The 90-second answer
The first number is the current spend on the specific resource, broken down by unit: dollars per month, or cost per request, per job or per GB. Without that baseline you cannot tell whether a proposed change saves anything, so every other claim about savings is unverifiable.
A concrete example. Say a batch job costs $1,800 a month. Before proposing any change I want to know where that figure comes from: instance count, hours run, and the unit rate. Only then can I compare options. Cutting instance count and cutting runtime can produce the same bill, but they carry different risks, so the baseline tells me which lever to pull first.
The baseline also sets the bar for the risk discussion. Frugality is not just cutting spend. It means spending where the return is clear and avoiding waste that does not change outcomes. A candidate who opens with the current number, then the projected number, then the risk to correctness or availability, is showing judgement, not just a cheap idea.
What I would not do is quote a saving from memory or from a vendor's price sheet without checking the measured figure from my own system. Pricing changes, and an estimate built on the wrong unit rate will be off by a large factor. Confirm the current rate from the provider's official pricing page before putting it in front of a team.
In practice I write the baseline as a single line in the proposal: current monthly cost, unit, and the source of the measurement. Everything after that is easier to review.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-91Tell me about a code review where you and a peer disagreed on a coding standard. How did you settle it, and what did the team end up adopting?
The 90-second answer
The dispute looked like taste, but it was about where errors cross a boundary. My peer wanted every service method to return a Result type. I wanted exceptions inside a module and a single translation step at the HTTP edge. Both of us had seen the same outage, and we disagreed about what it proved. I stopped arguing the rule in the review thread, took the disagreement off the diff, and turned it into a test we could both run against our own history.
Situation. A payments team of six, one service, about 40 handlers. In review, a Result wrapper was going into new code and I kept rejecting it. The review thread had 31 comments and no decision.
What I did. I pulled the last 14 incidents tagged as error-handling problems and classified each by where the error was lost. The count (hypothetical figures from our tracker, for illustration) was 9 swallowed errors inside a try block that logged and returned a default, 3 errors translated to the wrong HTTP status, and 2 timeouts misread as not-found. None of the nine swallowed errors would have been fixed by a Result type, because the bug was a catch that discarded the failure. That changed the argument. Neither style prevented the bug. What prevented it was a rule that a catch must either rethrow, map to a typed error, or be annotated.
I then proposed a two-sprint trial on one module, measured by the number of catch blocks without a typed outcome and the number of review comments raised about error paths. My peer proposed a condition: the trial also had to cover the retry path, since that is where a Result would have helped most. We agreed.
| Option | Swallowed-error risk | Review cost | Trial result (hypothetical) |
|---|---|---|---|
Result everywhere | unchanged, the catch still exists | high, every caller unwraps | 4 extra lines per call site |
| Exceptions, translate at edge | falls if catches are linted | low | 0 unannotated catches after lint |
Hybrid: Result in retry and payment core only | falls in the core | medium | retry path clearer, 2 unannotated catches |
What the team adopted. The hybrid, scoped. Result only in the payment core and retry logic, exceptions everywhere else, one translation table at the HTTP handler, and a lint rule that fails the build on a catch without rethrow, typed mapping or an annotation. The ADR was one page and named an owner for the translation table.
What I conceded. I had wanted the exception-only rule everywhere. My peer's retry argument was right, and the core module is where a dropped failure costs money. I said so in the ADR, with their name on that section.
The failure mode I watched for. A scoped standard drifts. Six months later the lint exemption list had grown to 40 entries. We reviewed it at each quarterly planning meeting and removed any annotation that had no ticket behind it.
The most useful thing I took from it: when a review thread stops moving, check whether the two people are arguing about the same failure. If they are not, write the failure down and test each option against it.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-92You've mentored an engineer who keeps escalating flaky-test triage to you. Compare two ways to get them handling it alone: scheduled pairing on each failure versus a written triage checklist they run first. Which one shows growth you can trust, and what would you check after stepping back?
The 90-second answer
The two approaches differ on where the learning lives. Pairing moves the reasoning into the session, so the engineer copies my moves while I am watching. A checklist moves the reasoning onto paper, so the engineer has to make each step explicit and can run it cold. I would start with the checklist, then use pairing only for the cases the checklist cannot resolve.
The checklist I'd hand over is short and ordered: reproduce on the same commit three times, check whether the failure correlates with a shared resource such as a port, a clock or a fixture, quarantine with an owner and a date if it still flakes, and only then escalate with the reproduction attached.
| Approach | What the engineer learns | Where it breaks |
|---|---|---|
| Pairing on each failure | Which questions I ask, in my order | Dependence: they stall when I am not in the room |
| Written checklist, run first | Which steps to take and why each one exists | Checklist-following without judgement on new failure shapes |
The trust signal is not the escalation count falling. A falling count can mean they stopped escalating and stopped looking, or that they quarantine everything. So after stepping back I pull the last five quarantined tests and ask them to defend each quarantine decision cold, with the reproduction in hand. A quarantine with no owner or no reproduction is a failure even if it reduced my pings.
Second check: give them a failure in a service they have not touched and see whether the checklist still produces a useful first hypothesis within fifteen minutes. If it only works in the service where they learned it, the growth was local.
Failure modes I watch for:
- Quarantine as deletion. Tests get marked flaky and never return. I count quarantined tests with no open ticket each week.
- Checklist ritual. Steps get ticked without the reproduction being attached. I read the attachments, not the checkboxes.
- Domain transfer failure. The checklist works on the service where it was learned and fails elsewhere. The cold task in an unfamiliar codebase is the test for that.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-93Tell me about a launch you owned that missed its target. What did you measure, and what change did you make afterwards?
Clarify first: I would pick a launch I owned end to end, and I would state the target before looking at the outcome, because a target set after the numbers arrive proves nothing. The example below is hypothetical, but it shows the level of detail I would give.
The setup. We moved the price-quote call in checkout out of the request path and into a batch job, aiming to cut checkout p99 from 420 ms to under 300 ms. The target was p99 under 300 ms with no conversion drop beyond 0.1 percentage points over a 7-day holdout at 10% of traffic.
What we measured. After one day at 10%, p99 was 310 ms, short of target. Conversion was flat within noise. Splitting latency by cache status showed the quote call was off the path for most requests, but a cache miss still went synchronous. The batch job ran every 15 minutes, so SKUs added inside that window had no quote and about 18% of requests missed. Hits averaged 180 ms and misses averaged 900 ms.
Arithmetic: 0.82 × 180 ms + 0.18 × 900 ms = 147.6 + 162 ≈ 310 ms at the mean. The tail sat well above that, and it was almost entirely the miss path. The aggregate p99 had hidden the two-humped shape for a week because nobody sliced it by cache status.
The change. I made three changes in order. First, I kept the batch job but added an on-demand fill on miss with a 50 ms budget, falling back to the last known price and marking the response as stale when the fill timed out. Second, I cut the batch interval to 60 seconds, which shrank the cold-SKU window from up to 15 minutes to 1 minute. Third, I added a dashboard that slices p99 by cache-hit status.
After the change, miss rate fell to 2.5%, miss-path p99 fell to 120 ms, and checkout p99 came in at 255 ms at 10%. I widened the rollout only after the holdout conversion check held.
What I got wrong. I assumed the batch job covered every SKU before I set the target. I should have checked coverage first, since a 15-minute refresh gap is a known property of that job and not a surprise.
The trade-off I accepted. Fallback prices can be up to one batch interval old. Finance approved stale quotes of up to 60 seconds for display only, while the charge still uses a fresh quote at confirmation. That gives the latency win without letting a stale price reach the customer's card.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-94When you take on a project that sits outside your team, what is the first thing you write down to define your boundary?
The 90-second answer
The first thing I write down is the list of things I own and the list of things I explicitly don't. Everything else follows from that split. Ownership alone is not enough, though. Without a named owner for each shared interface, the boundary is a wish, so I write the owned and not-owned columns first, then the interfaces where they meet, and only then start the work.
A concrete split
Suppose a nightly invoice export job sits in the billing repo and no team claims it. I wrote this before touching code:
| Column | Entry |
|---|---|
| Owned | Job code, its alerts, its runbook, its on-call rotation |
| Not owned | Ledger schema, tax rules, downstream finance dashboards |
| Interface | CSV export contract with a schema_version in the filename |
The interface row matters most. It is the seam where my responsibility stops and someone else's starts, so it has to be written in terms both sides can test against.
Why the not-owned column is not optional
Without it, every failure near the job becomes mine by default. A failure in the ledger's import endpoint would land on my pager even though I cannot fix it. Listing what I don't own stops that drift before it starts.
What I'd say aloud
I'd name the two columns, the interface, and the person who signed off on the split. That answers how I defined the boundary in one pass and gives the interviewer a clear place to probe next.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-95Your LRU cache passes every example-based test, yet a property test shrinks a failing run to four operations. Which invariants would you assert after every operation, and which boundary cases do generators tend to skip?
The 90-second answer
I check the cache against a reference model, not against expected values I wrote by hand. The reference is an OrderedDict with the same capacity. Every generated sequence of get and put runs against both, and after each step I compare the full recency order, not just the return values. A return-value check can pass while the eviction victim is wrong, and the next get then fails far from the bug. Comparing the order catches that on the step that caused it.
The invariants I assert after every operation: size never exceeds capacity; the list from most to least recent equals the model's order; every key in the hash map is in the list and the reverse holds; a get miss changes nothing.
from collections import OrderedDict
from hypothesis import strategies as st
from hypothesis.stateful import RuleBasedStateMachine, rule, invariant
CAP = 2
class LRUModel(RuleBasedStateMachine):
def __init__(self):
super().__init__()
self.impl = LRUCache(CAP)
self.ref = OrderedDict()
@rule(k=st.integers(0, 4), v=st.integers(0, 100))
def put(self, k, v):
self.impl.put(k, v)
if k in self.ref:
self.ref.move_to_end(k)
self.ref[k] = v
if len(self.ref) > CAP:
self.ref.popitem(last=False)
@rule(k=st.integers(0, 4))
def get(self, k):
expected = self.ref[k] if k in self.ref else -1
if k in self.ref:
self.ref.move_to_end(k)
assert self.impl.get(k) == expected
@invariant()
def same_recency_order(self):
assert self.impl.keys_mru_to_lru() == list(reversed(self.ref.keys()))
TestLRU = LRUModel.TestCaseThe keys_mru_to_lru() hook is a test-only accessor. I would not ship it, but I would keep it under test so the invariant can see the list.
Boundary cases generators skip by default
- Capacity 1. Every put of a new key evicts the only entry, and an update of the same key must not evict anything.
- Capacity 0. Either reject construction or define put as a no-op. Pick one and test that
getalways misses. - Update of a resident key at full capacity, where that key is not the LRU. This is the classic bug. Trace with capacity 2 (order shown most recent first):
| Step | Operation | Correct result and order | Buggy result and order |
|---|---|---|---|
| 1 | put(1, a) | [1] | [1] |
| 2 | put(2, b) | [2, 1] | [2, 1] |
| 3 | get(1) returns a | [1, 2] | [1, 2] |
| 4 | put(1, c) | update in place, [1, 2], size 2, nothing evicted | evicts LRU key 2 first, then updates 1: [1], size 1 |
| 5 | get(2) | returns b | returns -1 |
The buggy version picks its victim before checking whether the key already exists. Here the victim is the LRU entry 2, which is unrelated to the key being written, so an entry that should survive is lost. The example-based tests usually use fresh keys or update the key that is already LRU, which is why they pass.
- A
geton a missing key must not touch recency, or a failed lookup can promote something else. - Repeated
getof the same key should be idempotent in order. - Integer keys in a small range such as 0 to 4 produce collisions often. Wide random keys almost never do.
Why the shrinker matters
When the property fails, Hypothesis shrinks the sequence toward a minimal counterexample. A five-operation failure like the trace above is a usable bug report. Without shrinking, a 300-operation random log is nearly useless.
Where this approach stops
The model is only as correct as its OrderedDict, and a single-threaded property test cannot find concurrency bugs. Under the cache lock, I test interleavings separately with a small number of threads and a fixed seed, and I check that the eviction policy's update runs inside the same critical section as the map write. A single-threaded test will never reach a race between a hit's recency update and a concurrent eviction.
If the implementation uses a doubly linked list with a sentinel head and tail, I also assert that every node's prev and next pointers agree. Pointer corruption can leave the order looking right for a while and then break after a later eviction.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-96A bounded queue's consumer occasionally panics on an empty slice, but the race detector reports nothing. Why can a clean -race run still miss this bug, and what test would reproduce it reliably?
The 90-second answer
The race detector only reports two unsynchronised accesses to the same memory, at least one a write, with no happens-before edge between them. If every access to the queue sits under the same mutex, there is no data race to report, even when the logic is wrong. This bug is a logic error about when the check happens, not a memory race.
Here is the buggy Take, which waits inside an if instead of a for loop:
func (q *Queue) Take() int {
q.mu.Lock()
defer q.mu.Unlock()
if len(q.items) == 0 {
q.cond.Wait() // bug: must re-check after waking
}
v := q.items[0]
q.items = q.items[1:]
return v
}Consider consumers A and B and a producer P, with A parked in Wait:
| Step | Thread | Action | items |
|---|---|---|---|
| 1 | A | lock, sees empty, Wait releases lock | [] |
| 2 | P | lock, append 1, Signal, unlock | [1] |
| 3 | B | lock first, sees 1, pops it, unlock | [] |
| 4 | A | reacquires lock, skips the re-check, reads items[0] | index out of range |
Every access is under q.mu, so -race stays silent. The bug is an ordering of lock acquisitions, and only a schedule that forces step 3 before step 4 exposes it.
To reproduce it deterministically, add a test hook that runs after Wait returns and blocks on a channel the test controls. The test waits until A is parked, puts one item, lets B take it, then releases A and checks the outcome. Sequence the steps with channels, never with time.Sleep. Sleeps are where flakiness comes from, because they assume a scheduler timing that CI does not guarantee.
Stress runs cover what a hook cannot, such as unknown schedules: go test -race -count=10000 -cpu=1,4,16 -run TestQueueStress. If the bad schedule happens in one of 5,000 runs, 10,000 runs find it with probability about 1 - (1 - 1/5000)^10000 ≈ 0.87. A clean pass is evidence, not proof. Fix the if into a for, then keep the deterministic test as a regression.
Assert invariants after each stress run, not only at the end: items put equals items taken plus items left, no value is delivered twice, and per-producer order is preserved.
Failure modes to name:
- The test passes under
-raceonly because the detector's slowdown hides the window. Run the suite with and without-race. - Test hooks change timing or leak into production builds. Compile them out, or guard them so release builds never set them.
- Hand-written hooks only cover interleavings you thought to write. For lock-free code, use a systematic checker such as Rust's
loom, which explores interleavings within a bounded model of atomics.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-97A pull request adds a loop that checks `if line.sku not in out` inside a loop over every order line in a batch of 50,000. Walk me through how you would review it: the complexity regression, how you would confirm it, and the fix you would propose.
The 90-second answer
The regression is the membership test. out is a Python list, so x in out scans from the front until it finds x or reaches the end. Each check costs O(k), where k is the current length of out. The outer loop is O(L) over the L lines, so the nested pair of loops is O(L·k), which is O(L²) when most SKUs are distinct. I would reject the change as written and ask for a set alongside the list, keeping the list only for order.
# before (flagged in review)
def unique_skus(orders):
out = []
for order in orders:
for line in order.lines:
if line.sku not in out:
out.append(line.sku)
return out
# after
def unique_skus(orders):
seen = set()
out = []
for order in orders:
for line in order.lines:
if line.sku not in seen:
seen.add(line.sku)
out.append(line.sku)
return outArithmetic for the review comment. With L = 50,000 distinct lines, the list version makes about L²/2 = 1.25 × 10⁹ string comparisons in the worst case. The set version makes about 50,000 hash lookups and 50,000 inserts. The set holds O(distinct) extra memory, which is the price of the speedup.
Trace. Input lines A, B, A. Line 1: A not in seen, add it, append, out = [A]. Line 2: B is new, out = [A, B]. Line 3: A is in seen, skipped. Result [A, B], first-seen order preserved.
How to confirm it rather than assume it. Benchmark on CPython with synthetic batches of 5k, 20k and 80k distinct lines. The list version should roughly quadruple in time each time n doubles. The set version should roughly double. A profile showing time inside list __contains__ settles the cause and ends the argument about whether the batch size is realistic.
Failure modes to check in the same review.
- SKU objects with a
__hash__that disagrees with__eq__will produce silent duplicates in the set version and must be fixed first. - If the SKU type is unhashable, sorting then deduplicating costs O(L log L) and loses first-seen order unless you track positions.
- A set keyed on mutable objects breaks if the key changes after insertion.
I would also ask whether the batch size is bounded. If it is always under a few hundred lines, the list version is fine and the comment becomes a style note, not a blocker.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-98When you estimate scope with unknowns, what should your range be built around?
The 30-second answer
Build the range around a most-likely point, with an optimistic and a pessimistic bound, and state the assumption behind each bound. A single date hides the unknowns. A range with no named assumptions is just padding.
Why this shape. A strong estimate is three numbers plus a reason. Optimistic (O) is what happens if the unknowns resolve well. Most likely (M) is your best single guess. Pessimistic (P) is what happens if the riskiest assumption fails. Three-point (PERT) estimation combines them as (O + 4M + P) / 6, which weights the most-likely case most heavily.
Hypothetical figures: O = 5 days, M = 7, P = 15. Expected = (5 + 28 + 15) / 6 = 8 days. Quote it as "about 8 days, between 5 and 15, and the 15 end assumes the payments API changes version."
Name the assumptions. Each bound should trace to one assumption you can check. "The API stays on v2" is checkable. "Things might take longer" is not. The reader should be able to see what would have to be true for the optimistic end to hold.
Checkpoints. Tie each assumption to a point where you will know whether it holds. A spike on day 2 that tests the API assumption narrows the range. If the range does not shrink after a checkpoint, the unknown is larger than you thought, and you say so.
Failure modes. Committing to the pessimistic number as the date wastes capacity. Quoting only a single number hides the risk. Detect a bad estimate by recording which assumption broke on each miss. The same assumption breaking twice is a process problem, not bad luck.
Follow-up. How do you use past velocity? Only if the historical work was the same kind. Velocity from CRUD endpoints says little about a schema migration.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-99A Java service's old generation climbs steadily between full GCs over six hours under steady load. Walk me through how you find the leaking allocation site and prove the fix works.
The 90-second answer
A sawtooth is not a leak. A leak is a rising floor: old-generation occupancy measured just after a full GC keeps climbing at a constant rate under constant load. I confirm the floor first, then find what holds the references, then find where they were allocated, then prove the slope changed.
Step 1: separate retained from allocated. Turn on GC logging (-Xlog:gc*) and read occupancy just after each full or mixed collection, not before. Allocation rate tells you churn. Post-GC occupancy tells you retention.
Step 2: two dumps at the same request count. Take jcmd <pid> GC.heap_dump /tmp/a.hprof at roughly 1.4 M requests and again at 2.9 M. The default dump contains only live objects, so each dump is itself a post-GC floor. Dump a drained canary, not a production instance serving traffic, because the dump pauses the process.
Step 3: histogram, then dominators. jmap -histo:live is fast for spotting the class that grows with requests. Eclipse MAT's dominator tree and Leak Suspects report find the retaining path. Instance count alone misleads: a class with few instances can retain most of the bytes.
Step 4: get the allocation site, not only the holder. The holder says who keeps the object. The allocation site says why it was created. Record with jcmd <pid> JFR.start settings=profile and enable jdk.OldObjectSample with path-to-gc-roots=true. That captures stack traces and GC root paths for sampled long-lived objects.
| Elapsed | Requests served | Old gen after GC | Live RequestContext |
|---|---|---|---|
| 1 h | 1.44 M | 1.10 GB | 212 k |
| 3 h | 2.88 M | 1.31 GB | 421 k |
Hypothetical figures, but the arithmetic is the point. 210 MB over 1.44 M requests is about 146 bytes retained per request, and the RequestContext count doubles with the request count. One retained context per request is the signature to chase.
The retaining path ran through a static Map<RequestContext, Timer> in an interceptor. Its removal call sat only on the success path. Timeouts threw before the removal, so the entry stayed. JFR's sampled stack at before() showed the allocation site, and the dominator path showed the static field as the root.
Step 5: prove the fix. A flat-looking graph is not evidence. Deploy the fix to a canary that receives the same traffic mix and run at least three hours. Compare the post-GC slope in bytes per request against the baseline. A bounded cache rises and then plateaus, while a leak keeps rising, so check which shape you see. Take a second dump at the same request count and confirm the class no longer dominates. Because the bug lived on the error path, inject timeouts in staging and assert that the map size returns to the in-flight count after a drain. Keep that as a regression test.
Scrub heap dumps before sharing them, since they contain request payloads and credentials.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-100Eight engineers own one codebase that deploys as a single artefact. Billing and search share a release train. Explain why splitting billing into its own service does not remove the deployment coupling if the two still change together, and what a network call adds that an in-process call does not.
The 90-second answer
Splitting billing out of a monolith only removes deployment coupling if the two teams can change and ship their code without coordinating. If billing and search still ship together because a shared field or a shared database table has to change in lockstep, the coupling has moved into an API contract. You now have the same coupling plus network failure modes.
An in-process call is a function call: it either returns or throws, and both sides share one transaction and one process lifetime. A network call can time out after the server has already done the work, can be retried, and can reach a version of the callee that does not understand the new field yet. Those three cases are what you must design for once the call crosses a boundary.
Mechanism: coupling survives a split
Suppose billing and search both read order.status, and a release adds a new status partially_refunded. In the monolith, one commit changes the enum, the billing code, and the search filter together, and one deploy ships it. After the split, billing emits partially_refunded through its API, and search rejects unknown enum values. If search deploys first, it crashes on the new value. If billing deploys first, it sends a value search cannot parse. The fix is an ordering constraint, so the two services are coupled by a contract instead of by a release train.
The test that separates the two cases is simple: can billing ship a change that search does not yet understand, and can search ship a change that billing does not yet emit, without either breaking the other? If yes, the split buys independence. If no, it does not.
What a network call adds
| Concern | In-process call | Network call |
|---|---|---|
| Result | returns or throws | returns, errors, or times out with unknown outcome |
| Retry | not needed | needs an idempotency key on writes |
| Version skew | same build | caller and callee versions differ during rollout |
| Latency | nanoseconds to microseconds | typically milliseconds, with a long tail |
| Transaction | one DB transaction | separate transactions, so a saga or outbox |
The timeout case matters most. Billing charges a card, the response is lost, and the caller times out and retries. Without an idempotency key on the charge, the customer is billed twice. With one, the second call returns the first result. That is a mechanism you can check in a design review: every write that crosses the boundary needs a key the callee stores and replays.
Failure modes to name
- Unknown-outcome writes: a timed-out call may or may not have happened. Detect it by logging the idempotency key on both sides and reconciling counts daily.
- Chatty calls: a page that makes 40 sequential calls now pays 40 round trips. Detect it with call count per request in traces and p99 per endpoint.
- Shared table kept after the split: if search still reads billing's table directly, the coupling is invisible in the API. Detect it by listing who holds read or write credentials to each table.
What I would do first
With eight engineers, I would enforce a module boundary inside the monolith first: separate packages, no direct table access across packages, and an explicit interface for billing. If the release train still blocks billing after that, I would split, and I would define the contract's compatibility rule before the first deploy: new fields are optional, enums are open, and removals wait one release.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.