Skip to content
Tech Interview Prep
Technical interview guide

1-D Dynamic Programming

Breaking a problem into overlapping subproblems indexed by a single variable, solved once each and reused.

Minutes to read
3
Practice MCQs
25
Interview Q&A
25
Edition
v8
Editorial status
Reviewed

Scope: Language-neutral, with memoisation and recursion behaviour cited from CPython 3.14.

Interview Q&A

Treat each question like a live interview question: answer out loud first (structure, assumptions, tradeoffs), then open the model answer to spot gaps and rehearse a tighter follow-up.

Curated: · Written: · Reviewed:

25 questions

Q&A-1

Explain the two conditions for dynamic programming and how it changes a production decision.

Answer

Two conditions, and they do different jobs. Optimal substructure: the best answer to the whole problem is assembled from best answers to subproblems. That is what makes a recurrence correct. Overlapping subproblems: the naive recursion reaches the same state many times. That is what makes caching worth it. The first is a correctness property, the second is a cost property. You can have the first without the second, and then DP is correct but pointless.

The production decision is rarely "should I use DP". It is "does the state space fit the budget". Take a fuzzy-match endpoint that scores how close two strings are with edit distance. States are (i, j): prefix i of the source against prefix j of the target. Overlap is real: the naive recursion reaches d[i][j] along exponentially many distinct paths, so the table computes each cell once instead of re-deriving it. Optimal substructure holds: d[i][j] is the minimum of three neighbours plus a cost.

Trace it on "cat" vs "cut":

""cut
""0123
c1012
a2112
t3221

Each cell is min(d[i-1][j]+1, d[i][j-1]+1, d[i-1][j-1] + (s[i]==t[j] ? 0 : 1)). The diagonal is free when the characters match, which is why d[1][1] is 0 and d[3][3] is 1: one substitution turns "cat" into "cut".

Now the decision. 200-character strings are 40,000 cells; at 4 bytes each that is 160 KB and a few hundred microseconds of work. 10,000-character strings are 100 million cells: 400 MB per request, and roughly a second of cell updates. That is the moment DP stops being a free win: you either cap the input at, say, 512 characters, or switch to a banded DP that fills only a diagonal strip of width k, or drop to a cheaper heuristic. The two conditions told you the recurrence was right; the arithmetic tells you whether you can afford it.

Two failure modes worth naming. First, no overlap: a tree walk where each node is visited once. The memo table never hits, and you have added a hash lookup per node for nothing. Detect it by instrumenting the cache: hit rate near zero on real traffic. Second, no optimal substructure: longest simple path in a graph with cycles. The recurrence looks fine, the answers are wrong, and it survives testing because small acyclic inputs happen to work. Detect it with a brute-force reference on small inputs, or by checking that your state captures everything the future depends on.

So: state both conditions, then price the state space. If the table fits, DP is usually the simplest correct thing. If it does not, the conditions being satisfied does not help you.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-2

How would you reason about defining the state in a system you own?

Answer

Core answer (first 90 seconds)

First I pin down what "state" means here, because that decides the design. I mean the facts the system is the authority for: the ones that must still be true after a restart and that no other service can reconstruct. Everything else is either derived from those facts or scoped to a single request. So the reasoning is: name the source of truth, name its single writer, then decide what to derive.

Assumption I'd state out loud: one service owns a bounded domain, and each fact has exactly one writer. If two services can write the same fact, no state definition saves you.

Then three questions, in order:

  1. Must this survive a restart? If yes it's durable state and needs a store with a durability story. If it can be recomputed from durable state, it's derived and should not be a second source of truth.
  2. Who is the single writer? One owner per fact. Derived state has no writer: it has a builder.
  3. What's the scope? Request-scoped, session-scoped, entity-scoped, or system-scoped. Scope decides lifetime and where it lives.

Classify, then place

KindExampleStoreRebuildable?
Source of truthorder rows, line itemsPostgresNo: back it up
Derivedorder total, search indexcomputed / Redis / indexYes, from source
Ephemeralrequest context, in-flight retry countprocess memoryN/A

The rule: derived state is allowed to be wrong for a bounded window; source-of-truth state is not allowed to be wrong at all. That asymmetry decides where you put a cache and how you detect drift.

Worked example: order total

Say an order has line items and a total. Two options:

  • Store total on the order row. Reads are one row. But now every line-item change must update the total in the same transaction, or the two disagree.
  • Compute total = SUM(line_items.price * qty) on read. No invariant to maintain, but every read pays a join.

Hypothetical figures: 2,000 reads/sec of an order page, 5 writes/sec of line items. Storing the total turns 2,000 joins into 2,000 single-row reads and adds one write per line-item change: cheap. The cost is the invariant: the total must be updated in the same transaction as the line item, or you get drift. So store it, but make the invariant explicit and add a reconciliation job that recomputes totals nightly and alerts on any mismatch.

Failure modes and detection

  • Dual write. Writing the DB and a cache in the same request without a transaction. They diverge on partial failure. Detect with a reconciliation pass; fix by making the cache derived and rebuildable, never authoritative.
  • Derived state with no invariant. A stored total that nothing checks. Detect by recomputing from source on a schedule and alerting on mismatch.
  • Two writers. Two services updating the same row. Detect with optimistic concurrency (a version column) and lost-update alerts.

Trade-offs

Normalize when correctness matters and read volume is low; denormalize when reads dominate and you can afford the invariant. Event-sourcing keeps every fact as an append-only log: good for audit, but you now own projection rebuilds and eventual consistency. Current-state storage is simpler; you lose history.

The senior move: state the source of truth first, make derived state explicitly rebuildable, and reach for measurement (read/write ratio, reconciliation cost) only when the decision turns on cost rather than correctness.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-3

Walk through the transition, including where engineers most often get it wrong.

Answer

Clarify first. "The transition" only means something once you name the DP. I'll take the canonical last-decision transition: House Robber (LeetCode 198). The maximum sum of a non-adjacent subsequence of nums. If you meant a different recurrence, the shape below is the same and the failure modes are the ones to check.

The transition. Let dp[i] be the best total using the first i houses. The last decision is about house i-1: either you rob it, in which case house i-2 is off the table and you add nums[i-1] to dp[i-2]; or you don't, and you keep dp[i-1].

dp[i] = max(dp[i-1], dp[i-2] + nums[i-1])
dp[0] = 0, dp[1] = nums[0]

Why "last" matters: the two branches partition the solution space. Every valid selection either contains house i-1 or it doesn't, and there is no third case. That is the whole correctness argument. If the decision you branch on isn't the one that determines the rest of the state, the partition breaks.

Trace. nums = [2,7,9,3,1], rolled to O(1) space:

Python
def rob(nums):
    prev, cur = 0, 0          # prev = dp[i-2], cur = dp[i-1]
    for x in nums:
        prev, cur = cur, max(cur, prev + x)
    return cur
xprev (dp[i-2])cur (dp[i-1])max(cur, prev+x)
2002
7027
92711
371111
1111112

Returns 12 (houses 0, 2, 4 → 2+9+1). O(n) time, O(1) space.

Where engineers get it wrong.

  1. Off-by-one in the state definition. dp[i] = "best using first i" versus "best ending at i" changes the base cases. Mixing them gives dp[1] = nums[0] in one and dp[0] = nums[0] in the other; the recurrence still looks right and the answer is wrong by one element.

  2. Branching on a decision that isn't last. House Robber II wraps the array in a circle. Applying the same recurrence directly is wrong, because whether you can rob house n-1 depends on whether you robbed house 0: the last decision isn't independent. The fix is to run the linear recurrence twice, once on nums[:-1] and once on nums[1:], and take the max.

  3. A greedy shortcut that looks equivalent. "Take every other house" fails on [2,1,1,2]: even indices sum to 3, odd to 3, but the optimum is 4 (houses 0 and 3). The recurrence finds it because dp[3] = max(dp[2]=3, dp[1]+2=4).

  4. Overlapping cases. If you write the "skip" branch as dp[i-1] but also let the "take" branch fall back to dp[i-1] when nums[i-1] is negative, the two branches overlap and you can double count. Keep them disjoint.

Alternatives. Top-down memoization is easier to derive and reads closer to the recurrence, at O(n) stack and O(n) space. The rolling two-variable version is O(1) space but only works because the recurrence reaches back exactly two states. If the constraint is "no two within k", the state needs the last k+1 values and you keep a deque: the two-variable trick stops working.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-4

What does base cases guarantee, and what does it deliberately leave open?

Answer

A base case guarantees two things, and deliberately leaves three open.

What it guarantees. Termination and the anchor value. The base case is the state where the recurrence stops calling itself, so every chain of recursive calls is finite: that is well-foundedness, and it is the only thing that makes the recursion defined at all. It also fixes the value at that state by stipulation, not derivation: dp[0] = 0 in coin change is true because "zero coins make zero" is the definition of the empty solution, not because the recurrence computed it. The base case is the fixed point the recurrence is anchored to.

What it leaves open. (1) The inductive step: base cases say nothing about whether dp[a] = min(dp[a-c] + 1) is correct for a > 0; that is a separate optimal-substructure argument. (2) Completeness of the base set, which states are terminal is a modelling decision, and a missing terminal state means the recursion never bottoms out. (3) The value of an unreachable state: base cases do not tell you what an impossible state holds.

That third one is what interviewers push on. Take coins = [1, 2, 5], target = 11, dp[a] = fewest coins to make a, dp[0] = 0, unreachable = inf:

a01234567891011
dp[a]011221223323

dp[11] = 3 (5+5+1). The base case dp[0] = 0 is the only stipulated value; every other cell is derived, and the table is correct only because the inductive step is.

Now the sentinel choice, which is a real trade-off:

RepresentationWorks whenCost
inf (min) / -inf (max)recurrence does arithmetic on the value; inf + 1 = inf stays absorbingfloat arithmetic; inf can leak into output
-1value is only compared, never addedevery min needs a guard, because -1 + 1 = 0 looks valid
separate reachable[] boolyou want no sentinel arithmetic at alldoubles memory, two arrays to keep in sync

Deciding criterion: does the recurrence add to the state value? If yes, pick a sentinel absorbing under the operation (inf for min) or guard explicitly. If the value is only compared, -1 is fine.

The failure is concrete. coins = [2], target = 3, unreachable initialised to 0: dp[0]=0, dp[1]=0, dp[2]=min(dp[0]+1)=1, dp[3]=min(dp[1]+1)=1. It reports one coin for amount 3, which is impossible. Zero is a legitimate value, so it is indistinguishable from reachable. Detect it by asserting dp[target] != SENTINEL before returning, and by testing a target you know is unreachable.

So: base cases guarantee termination and the anchor value; they leave open the inductive step, the completeness of the base set, and the representation of unreachable states. Only the first is a guarantee: the rest are decisions you have to make and defend.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-5

Describe memoisation versus tabulation and the evidence you would collect before relying on it.

Answer

Core answer

Both compute the same recurrence; they differ in evaluation order. Memoisation is top-down: you write the recurrence as a recursive function and cache results, so only states reachable from the entry point are ever computed, and the call stack carries the dependency order. Tabulation is bottom-up: you fill a table in an order where every dependency is already computed, iteratively, with no call stack.

The decision turns on two measurable things: what fraction of the state space is reachable, and how deep the recursion goes. If reachable states are a small fraction of the full space, memoisation wins on work. If depth is large or you need predictable memory, tabulation wins.

Worked example: ways to reach exactly n with steps {2, 4}:

Python
from functools import cache

def memo(n):
    @cache
    def f(k):
        if k < 0:  return 0
        if k == 0: return 1
        return f(k - 2) + f(k - 4)
    return f(n), f.cache_info()

def tab(n):
    dp = [0] * (n + 1)
    dp[0] = 1
    for k in range(1, n + 1):
        dp[k] = (dp[k-2] if k >= 2 else 0) + (dp[k-4] if k >= 4 else 0)
    return dp[n]

For n=6: memo(6) calls f(6)→f(4)→f(2)→f(0)=1, f(-2)=0, so f(2)=1; f(0)=1 so f(4)=2; f(2) is a cache hit, so f(6)=2+1=3. cache_info().misses is 5 (states 6, 4, 2, 0, -2). tab(6) fills dp[0..6] = [1, 0, 1, 0, 2, 0, 3] and returns 3. Same answer; memo computed 4 non-negative states, tab computed 7.

Failure modes

  • Memoisation on a recurrence whose depth grows with n blows the stack. CPython's default limit is 1000 frames (sys.getrecursionlimit()), so a depth-n recurrence raises RecursionError around n≈1000. Tabulation has no such limit.
  • Memoisation pays per-state overhead: a dict entry plus a function frame. Tabulation pays for every state in the range, including unreachable ones.
  • Tabulation's full table can be replaced by a rolling window when the recurrence only looks back a fixed number of steps: the loop above needs only the last four values, so O(1) memory instead of O(n).

Evidence to collect before relying on it

  1. Reachable-state count. Instrument the cache: cache_info().misses is the number of distinct states actually computed. Compare to the full state space. If misses ≈ n, memoisation buys nothing on work.
  2. Recursion depth. Track the maximum depth reached (a counter incremented on entry, decremented on exit) and compare to sys.getrecursionlimit(). If max depth approaches the limit, tabulate or raise the limit deliberately.
  3. Memory. Measure peak allocation with tracemalloc around each version on the same input; that gives bytes-per-state for the cache versus the table.
  4. Wall time. Benchmark both with time.perf_counter() (or timeit) on representative inputs at several sizes, same machine, same input. Report the crossover size, not a single number.
  5. Where time goes. cProfile the memoised version to confirm the cost is in the recursion and cache lookups rather than the recurrence body.

Correctness first: both must return the same value on the same inputs before any of the above matters.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-8

Teach climbing stairs and counting paths to an engineer who has only seen it as a rule of thumb.

Answer

The problem. You have n stairs. Each move is 1 or 2 steps. Count the distinct sequences of moves that land exactly on step n. The count is Fibonacci: ways(n) = ways(n-1) + ways(n-2), with ways(0) = ways(1) = 1. For n = 5 the answer is 8.

Why the sum holds. Look at the last move. It is either a 1-step from n-1 or a 2-step from n-2. Those two sets of sequences are disjoint (they end with different moves) and together they cover every sequence reaching n. So the number of paths to n is the number to n-1 plus the number to n-2. That is the whole mechanism: a sum over predecessors, not a max, because you are counting, not optimising. The same shape gives grid path counting (dp[i][j] = dp[i-1][j] + dp[i][j-1], closed form C(m+n-2, m-1)) and the k-step variant dp[i] = sum(dp[i-j] for j in 1..k).

Base cases. ways(0) = 1: the empty sequence is one way to already be at the top. ways(1) = 1. Setting ways(0) = 0 makes every entry 0, because each value is a sum of predecessors that all trace back to it.

| n | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | |---|---|---|---|---|---|---|---|---|---|---| | ways | 1 | 1 | 2 | 3 | 5 | 8 | 13 | 21 | 34 | 55 | 89 |

Iterative, O(1) space.

Python
# Python 3.12
def climb(n):
    if n <= 1:
        return 1
    prev2, prev1 = 1, 1          # ways(0), ways(1)
    for _ in range(2, n + 1):
        prev2, prev1 = prev1, prev1 + prev2
    return prev1

Trace climb(5): start prev2=1, prev1=1. i=2 → (1, 2). i=3 → (2, 3). i=4 → (3, 5). i=5 → (5, 8). Returns 8, matching the table.

Alternatives and when to pick them.

  • Naive recursion f(n) = f(n-1) + f(n-2) is O(2^n) time, O(n) stack: fine for n <= 20, unusable at n = 45 (roughly 3.5e13 calls).
  • Memoised recursion is O(n) time, O(n) space; the natural choice when the recurrence is irregular (obstacles, variable step sets) and you want to compute only reachable states.
  • The iterative version above is O(n) time, O(1) space: the default for this exact problem.
  • Matrix exponentiation of [[1,1],[1,0]] is O(log n) time; worth it only when n is huge and you cannot afford the linear scan.
  • Binet's closed form gives ways(n) = F(n+1) directly, but floating-point error makes it unreliable past n ≈ 70; use it for reasoning, not for exact large answers.

Failure modes.

  • ways(0) = 0: the table collapses to all zeros. Detect by asserting climb(0) == 1 and climb(2) == 2 in tests.
  • Off-by-one on the empty staircase: n = 0 is one way (do nothing), not zero.
  • Recursion without memoisation: passes small tests, then hangs or overflows the stack around n = 40.
  • For the k-step variant, forgetting to cap the window at k predecessors turns it into the 2-step recurrence and silently undercounts.

Generalising. With obstacles, set dp[i] = 0 at blocked steps and keep the same sum; with a step set S, sum over dp[i-s] for s in S. The recurrence is unchanged: only the predecessor set moves.

Curated: · Written: · Reviewed:

Difficulty: Easy
Q&A-7

Where does the Fibonacci example and its lesson matter, and where is it irrelevant?

Answer

Short answer: the Fibonacci example demonstrates exactly one mechanism, memoization collapsing overlapping subproblems, and it is a poor model for dynamic programming as a discipline. It matters when the state is the function's arguments and the subproblems overlap; it stops being relevant the moment you have to discover the state, the subproblems don't overlap, or the recurrence has cycles.

Assumption I'm making explicit: the "lesson" is "cache a pure function keyed on its arguments." Everything below is conditional on that.

Where it matters

  • Isolating the mechanism. Naive fib recomputes the same subproblems; the cache turns the call tree into a DAG where each node is evaluated once. Nothing else in the example distracts from that.
  • Sanity-checking a memoization decorator or cache layer. If your cache doesn't cut the call count on Fibonacci, it won't cut it anywhere.
  • Whiteboard explanation of "overlapping subproblems": the phrase is otherwise abstract.

Where it's irrelevant

  • Disjoint subproblems. Merge sort, binary search, quicksort: no subproblem repeats, so a cache only adds memory and lookup cost.
  • State that isn't the arguments. Edit distance needs (i, j) prefix indices; 0/1 knapsack needs (item, remaining capacity). Fibonacci hands you the state; these problems make you define it, and that definition is the actual work.
  • Cyclic recurrences. Shortest paths on a graph with cycles: plain memoization never terminates because the dependency graph isn't a DAG. You need Bellman-Ford or Dijkstra instead.
  • State spaces too large to cache. If the reachable states don't fit in memory, top-down memoization is the wrong tool.

Artefact: the mechanism and its detection, in one file:

Python
from functools import cache

# naive: count the calls
def fib_naive(n): return n if n < 2 else fib_naive(n-1) + fib_naive(n-2)
# fib_naive(35) makes 29,860,703 calls  (2*F(36) - 1)

calls = 0
@cache
def fib(n):
    global calls
    calls += 1
    return n if n < 2 else fib(n-1) + fib(n-2)

fib(35)
print(calls)   # 36  -> one evaluation per distinct argument

The calls counter is the detection instrument: if distinct evaluations ≈ total calls, the subproblems don't overlap and the cache is dead weight.

The failure mode this invites. Treating Fibonacci as the template for all DP leads you to memoize without first defining the state, so the cache key is wrong and the hit rate is near zero. Detection: log cache hits and misses; a hit rate near 0 on a problem you believe has overlapping subproblems means the key is wrong. Cost: a memoized edit distance with a key that omits one index degrades from O(m·n) to exponential in the input length. On two 1,000-character strings that is the difference between ~10^6 and ~10^600 operations, i.e. it never finishes.

Alternatives and when to pick them. Top-down memoization (recursion + cache) is easiest to write from a recurrence and only computes reachable states, but it pays recursion depth: Python's default limit is 1,000 frames. Bottom-up tabulation has no recursion limit and better constants, but computes every state even the unreachable ones. Greedy is O(n log n) or better but only correct when the problem has the greedy-choice property, which Fibonacci-style DP problems generally don't.

Deciding rule: if the state is the arguments and the subproblems overlap, the Fibonacci lesson transfers directly. If you have to invent the state, or the subproblems are disjoint, or the recurrence cycles, it doesn't, and reaching for a cache there is the mistake.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-9

How do you formulate the recurrence relation and space-optimized state transition for the House Robber problem?

Answer

Core answer (first 90 seconds). Define dp[i] as the maximum loot obtainable from the first i houses, nums[0..i-1], with dp[0] = 0. House i-1 is either robbed or skipped:

  • Skip it: the best you can do is dp[i-1].
  • Rob it: house i-2 is now forbidden, so you add nums[i-1] to dp[i-2].

$$\text{dp}[i] = \max(\text{dp}[i-1],\ \text{nums}[i-1] + \text{dp}[i-2])$$

That is optimal substructure with an exchange argument: if an optimal solution for prefix i excludes house i-1, it must be optimal for prefix i-1 (otherwise swap in the better prefix); if it includes house i-1, it excludes i-2 and the remainder must be optimal for prefix i-2. Time is O(n), and the array costs O(n) space.

Space optimization. dp[i] reads only dp[i-1] and dp[i-2], so the array is dead weight. Roll two scalars, prev2 = dp[i-2] and prev1 = dp[i-1], both initialized to 0 (the empty prefix). Python 3.11:

Python
def rob(nums: list[int]) -> int:
    prev2 = prev1 = 0          # dp[i-2], dp[i-1]
    for x in nums:
        prev2, prev1 = prev1, max(prev1, x + prev2)
    return prev1

The tuple assignment evaluates the right-hand side before rebinding, so prev2 still holds the old dp[i-2] when max runs. O(n) time, O(1) space.

Worked trace, nums = [2, 7, 9, 3, 1]:

xprev2 beforeprev1 beforecurr = max(prev1, x + prev2)after
200max(0, 2+0) = 2(0, 2)
702max(2, 7+0) = 7(2, 7)
927max(7, 9+2) = 11(7, 11)
3711max(11, 3+7) = 11(11, 11)
11111max(11, 1+11) = 12(11, 12)

Result 12, from indices 0, 2, 4 (2 + 9 + 1).

Equivalent two-state formulation. Some interviewers prefer explicit take/skip states, which generalizes better to House Robber II and III: take[i] = skip[i-1] + nums[i], skip[i] = max(take[i-1], skip[i-1]), answer max(take[n-1], skip[n-1]). Same recurrence, one more variable.

Failure modes.

  1. Parity greedy. Summing even indices versus odd indices is wrong, not just suboptimal: [2, 1, 1, 2] gives 3 either way, but robbing indices 0 and 3 yields 4. The DP is required because the choice at i depends on the accumulated optimum, not on index parity.
  2. Clobbering state. In a language without simultaneous assignment, writing prev1 = max(prev1, x + prev2) before saving the old prev1 into prev2 feeds dp[i] back in as dp[i-2]. Use a temp or a tuple/parallel assignment.
  3. Negative values. With prev2 = prev1 = 0 the empty set is allowed, so negatives are handled correctly: the answer floors at 0. If the problem requires robbing at least one house, initialize both to -inf instead.
  4. Reconstruction. O(1) space discards history. To return the chosen indices, keep the O(n) array and backtrack: walk i from n down, take house i-1 when dp[i] != dp[i-1] and jump to i-2, otherwise step to i-1.
Python
def rob_path(nums: list[int]) -> tuple[int, list[int]]:
    n = len(nums)
    dp = [0] * (n + 1)                      # dp[i] = best using first i houses
    for i in range(1, n + 1):
        dp[i] = max(dp[i - 1], nums[i - 1] + (dp[i - 2] if i >= 2 else 0))
    take, i = [], n
    while i > 0:
        if dp[i] == dp[i - 1]:
            i -= 1
        else:
            take.append(i - 1)
            i -= 2
    return dp[n], take[::-1]

On [2, 7, 9, 3, 1] this returns (12, [0, 2, 4]).

  1. Circular variant (House Robber II). When house n-1 is adjacent to house 0, the answer is max(rob(nums[:-1]), rob(nums[1:])), with n == 1 returning nums[0] directly: the two calls cover the cases where the first or last house is excluded.

Curated: · Written: · Reviewed:

Difficulty: Easy
Q&A-12

How do you formulate the recurrence relation for the Coin Change problem (fewest coins to make up an amount), and what is its time and space complexity?

Answer

Define dp[a] as the minimum number of coins needed to make amount a, where coins is an array of positive integers and V is the target amount.

Recurrence Relation

  • Base case: dp[0] = 0 (zero coins are needed to make an amount of zero).
  • State transition: For each amount a from 1 up to V: $$\text{dp}[a] = 1 + \min_{{c \in \text{coins} \mid c \le a}} \text{dp}[a - c]$$
  • If no coin c <= a can form a valid sub-amount (or dp[a - c] is unreachable), dp[a] = \infty.

Implementation

Python
def coin_change(coins: list[int], amount: int) -> int:
    # Initialize with float('inf') to represent unreachable states
    dp = [float("inf")] * (amount + 1)
    dp[0] = 0

    for a in range(1, amount + 1):
        for c in coins:
            if a - c >= 0 and dp[a - c] != float("inf"):
                if dp[a - c] + 1 < dp[a]:
                    dp[a] = dp[a - c] + 1

    return dp[amount] if dp[amount] != float("inf") else -1

Complexity Analysis

  • Time Complexity: $O(V \times n)$, where $V$ is the target amount and $n$ is the number of coin denominations (len(coins)). We compute $V$ independent subproblems, and each subproblem iterates over $n$ coin choices to evaluate the minimum.
  • Space Complexity: $O(V)$ auxiliary space to store the 1-D array of size $V + 1$.

Critical Mechanics and Failure Modes

  1. Unbounded Knapsack Nature: Because each coin denomination can be reused arbitrarily, this is an unbounded knapsack variant flattened into 1-D over the state amount. You iterate over amounts sequentially, which allows transitions to pull from previously computed optimal values of the same coin within the same pass.
  2. Pseudo-polynomial vs. Strongly Polynomial: The input size of the target amount $V$ in binary is $B = \lceil \log_2(V + 1) \rceil$. An $O(V \cdot n)$ algorithm runs in $O(n \cdot 2^B)$ relative to the input length of $V$. When $V$ is small (e.g., $10^4$), the computation executes in milliseconds; when $V = 10^9$, an $O(V)$ table allocation fails with an out-of-memory error before computation even begins.
  3. Greedy Trap: A standard greedy choice (always picking the largest coin $\le a$) fails for non-canonical coin systems. For denominations [1, 3, 4] and amount = 6, greedy chooses 4 + 1 + 1 (3 coins), whereas the recurrence yields 3 + 3 (2 coins).

Curated: · Written: · Reviewed:

Difficulty: Easy
Q&A-13

What is the difference in state transition and inner loop iteration order between 0/1 knapsack and unbounded knapsack in a 1-D array?

Answer

In a 1-D compressed DP table dp[w], the state represents the maximum value achieved for capacity w. The difference comes down strictly to inner loop iteration order over capacities:

  • 0/1 Knapsack iterates capacity backwards (from W down to weight).
  • Unbounded Knapsack iterates capacity forwards (from weight up to W).

The Mechanism

In the canonical 2-D recurrence, dp[i][w] uses dp[i-1][...] for 0/1 knapsack, meaning each item can be selected at most once:

0/1:       dp[i][w] = max(dp[i-1][w], dp[i-1][w - weight] + val)
Unbounded: dp[i][w] = max(dp[i-1][w], dp[i][w - weight] + val)

When compressed to a single array dp[w], the array slot initially holds values from step i - 1.

  1. 0/1 Knapsack (Reverse order: w = W -> weight): When updating dp[w], the subproblem dp[w - weight] has not been overwritten in the current iteration yet: it still holds the value from item i - 1. This guarantees each item is taken at most once.

  2. Unbounded Knapsack (Forward order: w = weight -> W): When updating dp[w], dp[w - weight] was already updated in the current outer loop iteration for item i. Taking dp[w - weight] + val allows the same item i to be used repeatedly.

Python
# 0/1 Knapsack: loop backwards to prevent reuse
for weight, val in items:
    for w in range(W, weight - 1, -1):
        dp[w] = max(dp[w], dp[w - weight] + val)

# Unbounded Knapsack: loop forwards to allow reuse
for weight, val in items:
    for w in range(weight, W + 1):
        dp[w] = max(dp[w], dp[w - weight] + val)

Concrete Trace

Consider capacity W = 4 and a single item with weight = 2, val = 10. Initial dp = [0, 0, 0, 0, 0].

  • Forward (Unbounded):
    • w = 2: dp[2] = max(dp[2], dp[0] + 10) = 10
    • w = 4: dp[4] = max(dp[4], dp[2] + 10) = max(0, 10 + 10) = 20 (item used twice).
  • Backward (0/1):
    • w = 4: dp[4] = max(dp[4], dp[2] + 10) = max(0, 0 + 10) = 10
    • w = 2: dp[2] = max(dp[2], dp[0] + 10) = max(0, 0 + 10) = 10 (item used once).

Failure Mode

Reversing this direction produces silent semantic corruption: sweeping forwards in a 0/1 knapsack turns the program into an unbounded solver without throwing runtime errors or out-of-bounds exceptions, surviving basic unit tests if test inputs only contain items that cannot fit multiple times.

Curated: · Written: · Reviewed:

Difficulty: Easy
Q&A-11

How does Kadane's algorithm solve the maximum subarray problem in O(n) time and O(1) space, and how do you handle arrays where all elements are negative?

Answer

Kadane's algorithm operates on the principle of optimal substructure: the maximum subarray ending at index i is either the element nums[i] alone, or the element nums[i] added to the maximum subarray ending at i - 1.

Recurrence and State Reduction

Let dp[i] be the maximum sum of a non-empty contiguous subarray ending at index i:

$$\text{dp}[i] = \max(nums[i], \text{dp}[i-1] + nums[i])$$

The global maximum is the maximum over all indices:

$$\text{max_sum} = \max_{0 \le i < n} \text{dp}[i]$$

Because computing dp[i] depends strictly on dp[i-1], we do not need to retain an array of size $n$. Tracking a single variable current_sum reduces space complexity from $O(n)$ to $O(1)$ while visiting each element once in $O(n)$ time.

Python
def max_sub_array(nums: list[int]) -> int:
    if not nums:
        raise ValueError("Array cannot be empty")

    current_sum = max_sum = nums[0]
    for x in nums[1:]:
        current_sum = max(x, current_sum + x)
        max_sum = max(max_sum, current_sum)
    return max_sum

Trace with Mixed Values

For nums = [-2, 1, -3, 4, -1, 2, 1, -5, 4]:

Indexxcurrent_sum = max(x, current_sum + x)max_sumAction
0-2-2-2Initial state
11max(1, -2 + 1) = 11Reset start at index 1
2-3max(-3, 1 + -3) = -21Extend
34max(4, -2 + 4) = 44Reset start at index 3
4-1max(-1, 4 + -1) = 34Extend
52max(2, 3 + 2) = 55Extend
61max(1, 5 + 1) = 66Extend (subarray: [4, -1, 2, 1])
7-5max(-5, 6 + -5) = 16Extend
84max(4, 1 + 4) = 56Extend

Result: 6.

The All-Negative Case

A common implementation flaw initializes max_sum = 0 and clamps current_sum using current_sum = max(0, current_sum + x). If the problem contract permits an empty subarray ($L = 0$), returning 0 is correct. However, in standard non-empty subarray specifications, if given nums = [-8, -3, -5], returning 0 is incorrect.

By initializing both current_sum = nums[0] and max_sum = nums[0], the transition max(x, current_sum + x) compares starting fresh with the single negative element against extending an even smaller negative sum. On [-8, -3, -5], the algorithm produces:

  1. x = -8: current_sum = -8, max_sum = -8
  2. x = -3: current_sum = max(-3, -11) = -3, max_sum = max(-8, -3) = -3
  3. x = -5: current_sum = max(-5, -8) = -5, max_sum = max(-3, -5) = -3

The algorithm correctly returns -3 (the least negative singleton) without branching or special-case checks.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-10

How would you test a claim that the system depends on ending-here versus best-so-far?

Answer

The claim is falsifiable, so test it by falsification: build inputs where the two quantities diverge, then check which one the system's output tracks. If you cannot make them diverge, the claim is untestable as stated.

Three methods, cheapest first:

  1. Differential test. Implement both variants (one that reports ending_here, one that reports best) and run them over a corpus. Any input where the outputs differ is a witness that the distinction matters. If nothing in the corpus separates them, the claim is unsupported by that corpus, not proven false.

  2. Mutation test. Take the real implementation, mutate the report line to return ending_here, and run the existing suite. If the suite still passes, the suite does not depend on the distinction: the claim is false for that suite.

  3. Instrumentation. In a running system, log both values per step and compare the emitted answer against each. This is the only method that tests the deployed system rather than a model of it.

Constructing a divergence input. The two quantities coincide whenever the best subarray ends at the last index. So the witness has the shape: a peak, then a tail that drags ending_here down without beating best.

Python
def kadane(a):
    ending_here = best = a[0]
    for v in a[1:]:
        ending_here = max(v, ending_here + v)
        best = max(best, ending_here)
    return best, ending_here

Run kadane([-2, 1, -3, 4, -1, 2, 1, -5, 4]):

vending_herebest
-2-2-2
111
-3-21
444
-134
255
166
-516
456

Returns (6, 5). The correct answer is 6; the ending-here value is 5. A test asserting 6 that passes is evidence the system reports best; a test asserting 5 is evidence it reports ending_here.

What each method decides. Differential and mutation testing decide the claim about the code you have. Instrumentation decides it about the system you run. Neither tells you the claim is true in general: only that you found, or failed to find, a witness.

Failure modes. All-positive arrays never diverge (ending_here == best at every step), so a corpus of them tests nothing. Ties hide divergence too: if the best subarray happens to end at the last index, both values agree. And a passing suite proves only that the suite lacks a witness, not that the quantities are interchangeable: the mutation survives because the tests are weak, not because the distinction is unnecessary.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-15

How do you reconstruct the optimal sequence of choices in a 1-D DP problem rather than just computing the optimal value?

Answer

Computing the optimal scalar value tells you what the optimum is, but not which transitions produced it. To reconstruct the sequence, you have two mechanisms: storing an explicit back-pointer array during the forward pass, or re-evaluating the recurrence backward using the completed DP array.

Mechanism 1: Explicit Back-Pointers (parent array)

Whenever a transition improves the state at index i, store the predecessor index or choice token in parent[i]. Once the table finishes, start at the terminal state and trace backward until reaching a base state, then reverse the collected path.

Mechanism 2: Re-evaluating the Recurrence (Zero Extra Memory)

If the full 1-D table dp is preserved, you do not need a second array. At state i, check each valid previous state i - step and transition cost cost to find which satisfies dp[i] == dp[i - step] + cost. Step into that state and repeat.

Python
def coin_change_with_path(coins: list[int], amount: int) -> list[int]:
    # dp[a] = min coins to make amount a
    dp = [float("inf")] * (amount + 1)
    parent_coin = [-1] * (amount + 1)
    dp[0] = 0

    for a in range(1, amount + 1):
        for c in coins:
            if a - c >= 0 and dp[a - c] + 1 < dp[a]:
                dp[a] = dp[a - c] + 1
                parent_coin[a] = c

    if dp[amount] == float("inf"):
        return []

    # Traceback: O(k) where k is the number of coins chosen
    path = []
    curr = amount
    while curr > 0:
        coin = parent_coin[curr]
        path.append(coin)
        curr -= coin
    return path

Worked Trace

With coins = [1, 3, 4] and amount = 6:

  • Forward pass fills dp = [0, 1, 2, 1, 1, 2, 2].
  • parent_coin records the coin that achieved each optimum: [-1, 1, 1, 3, 4, 1, 3] (for 6, dp[6-3] + 1 = dp[3] + 1 = 2, equal to dp[6-4] + 1 = dp[2] + 1 = 3; picking 3 gives minimal steps).
  • Reconstruction starting at curr = 6:
    1. parent_coin[6] = 3 $\rightarrow$ path = [3], curr = 3
    2. parent_coin[3] = 3 $\rightarrow$ path = [3, 3], curr = 0
  • Returns [3, 3], total length 2.

Trade-offs and Failure Modes

  1. The Rolling Array Conflict: If you optimize space from $O(n)$ to $O(1)$ by retaining only dp[i-1] and dp[i-2], backward reconstruction via re-evaluation becomes impossible, and keeping an explicit parent array restores space complexity back to $O(n)$. You cannot have both $O(1)$ space and full path reconstruction in the general case.
  2. Floating-point Drift or Ties: If re-evaluating transitions with floating-point values, roundoff can prevent dp[i] == dp[i - step] + cost from matching. An explicit integer parent token avoids precision failure.
  3. Ambiguity on Equal Costs: When multiple choices produce the same optimum, explicit tracking deterministically records whichever tie-breaking policy ran during the forward pass.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-16

What failure would you inject to check a team's understanding of longest increasing subsequence?

Answer

I'd inject an input that is legal, small enough to trace by hand, and whose correct answer a memorised implementation gets wrong, then ask the team to predict the output before they run it. The one that does the most work is [3, 4, 1] with the requirement to return the subsequence, not just its length.

Why that one: the standard O(n log n) patience-sorting solution keeps a tails array whose length is the LIS length, but tails is not itself a subsequence. For [3, 4, 1] it ends as [1, 4], and 1 sits after 4 in the input, so [1, 4] is not a subsequence of [3, 4, 1] at all. A team that returns tails passes every test where the input happens to be sorted, or where they only ever check the length.

Python
import bisect

def lis_length(a):
    tails = []
    for v in a:
        i = bisect.bisect_left(tails, v)
        if i == len(tails):
            tails.append(v)
        else:
            tails[i] = v
    return len(tails), tails

Trace on [3, 4, 1]:

vbisect_left(tails, v)tails after
30 (== len 0)[3]
41 (== len 1)[3, 4]
10 (!= len 2)[1, 4]

Returns (2, [1, 4]). The length 2 is right; [1, 4] is not a valid answer. Correct LIS: [3, 4].

Two companions worth injecting in the same session, because each catches a different memorised shortcut:

  • [2, 2, 2]: strict vs non-decreasing. bisect_left gives 1; bisect_right gives 3. If the team can't say which one their code uses and why, they don't own the strictness decision.
  • [1, 5, 2, 3, 4]: greedy-from-the-front gives [1, 5], length 2; the answer is [1, 2, 3, 4], length 4.

How to run it: hand them the input, ask for the output and the subsequence on paper, then run. The failure you're looking for is not a crash: it's a confident wrong answer, or a correct length with a tails array handed back as the subsequence. That's the gap between having seen the algorithm and understanding what its state actually represents.

If they need reconstruction, the fix is predecessor links: store, for each position, the index of the tail it extended, then walk back. The tails array alone can't do it.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-6

A teammate proposes a design that hinges on the iteration order in tabulation. How do you evaluate it?

Answer

First question: is the order a correctness invariant or a performance choice? Those get evaluated differently, and the teammate's design usually doesn't say which it is. So I'd ask what each cell depends on: same row, previous row, or a cell the current pass may already have written.

If it's correctness, the recurrence reads a cell the same pass can overwrite. The canonical case is 0/1 knapsack in a rolling 1-D array: dp[c] = max value with capacity c, and for each item, for c from W down to w: dp[c] = max(dp[c], dp[c-w] + v). Descending is required. One item, weight 1, value 10, W = 3:

Descending: c=3 → dp[3] = max(0, dp[2]+10) = 10; c=2 → dp[2] = max(0, dp[1]+10) = 10; c=1 → dp[1] = max(0, dp[0]+10) = 10. Answer 10: the item used once.

Ascending: c=1 → dp[1] = max(0, dp[0]+10) = 10; c=2 → dp[2] = max(0, dp[1]+10) = 20; c=3 → dp[3] = max(0, dp[2]+10) = 30. Answer 30: the same item counted three times. Ascending silently solves unbounded knapsack.

So the review question is whether the wrong order can be written by accident and still pass tests. Here it can: the bug only appears when an item can be reused within the capacity, and a test with W < 2·min weight never exposes it. I'd ask for a differential test against brute-force enumeration on random small inputs, and for the invariant to be stated where the loop is: a comment naming the dependency, or better, a structure that makes the wrong order unrepresentable.

That leads to the alternative: remove the order dependence. Two ways. Top-down memoisation makes order implicit: the call graph computes dependencies on demand, so there's no loop direction to get wrong; cost is recursion overhead and O(nW) stack depth in the worst case. Or keep bottom-up but read from a previous row and write to a current row, so direction within a row is irrelevant; cost is one extra O(W) array. For W = 10^5 that's 800 KB of doubles: cheap insurance against a footgun that survives code review.

Note the direction is not a performance tradeoff. Both directions are O(nW) time and O(W) space; the choice is semantics. So "measure it" is the wrong instinct here: this is settled by reasoning and a differential test, not a benchmark.

Order is a genuine performance question in a different place: memory layout. A 2-D table of 10^4 × 10^4 doubles is 800 MB, so traversal matching the allocation is cache-friendly and the other direction thrashes. That's where you measure, and where the answer depends on the machine.

Failure modes to name: uninitialised or stale reads producing data-dependent wrong answers; a happy path that hides it; and an invariant that lives only in the author's head. Detection: differential testing against brute force, plus an assertion or a restructured loop that makes the wrong order impossible to write.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-14

When would you refuse a design because of space optimisation by rolling arrays?

Answer

I roll a DP only when the value is the deliverable and the recurrence reaches back one row. I refuse in four cases, and in each one I point at the number that decides it. Assume int32/int64 values, one core, a full table we could afford to allocate unless stated otherwise.

The path is the deliverable, not the value. Edit distance between two 10,000-character strings: the full table is 10^8 int32 cells, 400 MB; two rolling rows are 2 * 10,000 * 4 = 80 KB. If the only output is the distance, roll. If the alignment has to appear in a diff UI, the row-only version is not an option, and there are two priced alternatives. Hirschberg's divide-and-conquer recovers the alignment in O(min(m,n)) space and O(mn) time at roughly double the constant factor, so if the distance-only pass is 400 ms, budget about 800 ms. Knapsack is cheaper to rescue: 2,000 items by 50,000 capacity in int64 is 800 MB full, 400 KB rolled, and a parent bitvector at nW bits is 12.5 MB, 64x under the full table, with the item set recovered by a backward walk of n steps. Same reasoning when the table itself is the artefact, a DTW matrix someone inspects or a DP table the audit log retains.

The recurrence is not a window. Matrix-chain multiplication over 500 matrices has a 500x500 int64 table, 2 MB, which is small. But dp[i][j] depends on dp[i][k] and dp[k][j] for every k between i and j. No row can be dropped; you fill by interval length and keep the square. CYK parsing and optimal BST behave the same way. Calling it a memory optimisation here is a wrong answer with extra steps.

Two passes over the same table. Product-of-array-except-self needs prefix and suffix products. Change-point detection and best-split problems have the same shape: a forward pass then a pass that needs the suffix statistic. Either keep both tables or recompute one, and recomputing doubles time on a path that may already be at budget. I would keep the second table and say so in the design note.

The table is not the peak. A 1,000x1,000 int32 DP is 4 MB. A 5,000-node adjacency matrix in int64 is 25 * 10^6 * 8 = 200 MB. Rolling buys 2% of peak RSS and adds the bug class below. Refuse.

That bug class is worth naming exactly, because it is the one a reviewer catches. Rolling to a 1-D array and iterating capacity upward turns 0/1 knapsack into unbounded knapsack. One item, weight 2, value 10, capacity 4, dp initialised [0, 0, 0, 0, 0], iterating j from 0 to 4:

  • j=0: 0-2 < 0, skip, dp[0] = 0
  • j=1: 1-2 < 0, skip, dp[1] = 0
  • j=2: dp[2] = max(0, dp[0] + 10) = 10
  • j=3: dp[3] = max(0, dp[1] + 10) = 10
  • j=4: dp[4] = max(0, dp[2] + 10) = 20, the item used twice

Iterating j downward reads dp[2] before it is overwritten and dp[4] lands on 10, which is the real answer. In the in-place form, the order of writes is part of the algorithm, not a detail.

Two checks I ask for before agreeing to collapse anything. A test that runs the rolled result against the full-table result on random inputs up to 50 elements, and a peak-memory measurement, /usr/bin/time -v on Linux or tracemalloc in Python, showing the table was actually the peak. If it was not, the answer is no.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-20

What trade-off does cache keys and hashability force that a junior answer usually skips?

Answer

The 90-second answer. Hashability is the easy half. A dict key must be immutable with a consistent __hash__/__eq__, so list, dict and set are out and you reach for tuples, strings, ints or frozen dataclasses. The half that gets skipped is completeness: the key is a claim about everything the result depends on, and a key that omits a dependency returns a value computed under different conditions. That is a wrong answer, not a cache miss: nothing raises, nothing logs.

The two halves pull against each other. The cheapest hashable key is usually the incomplete one (an object's identity, a single id); the complete key is usually the expensive one (a deep tuple of every field the result reads). You are choosing where to pay.

Mechanism. functools.lru_cache (Python 3.2+, default maxsize=128) and functools.cache (3.9+, equivalent to lru_cache(maxsize=None)) build the key from the full argument tuple, positional and keyword. On a method, self is the first element of that tuple, hashed by identity via the default object.__hash__. The cache is keyed on which instance, not on what state that instance is in.

Python
from functools import lru_cache

class Counter:
    def __init__(self):
        self.n = 0
    @lru_cache(maxsize=None)
    def scaled(self, k):
        return self.n * k

c = Counter()
print(c.scaled(2))   # 0
c.n = 10
print(c.scaled(2))   # 0, not 20

Trace: the first call keys on (c, 2). c hashes by identity, self.n is 0, result 0 is stored. The second call builds the same key (same object, same identity hash, 2 == 2) so it is a hit and returns the stored 0. self.n is now 10, so the correct value is 20. The cache is silently wrong.

The other end of the constraint is a hard error rather than a silent one:

Python
@lru_cache(maxsize=None)
def total(xs):
    return sum(xs)

total([1, 2, 3])
# TypeError: unhashable type: 'list'

The trade-off, stated. You pick a key on two axes:

Key choiceHit rateCorrectness risk
Identity (self, id(obj))low: equal objects don't sharehigh: mutable state invisible
Value (__eq__/__hash__ on fields)high: equal objects shareneeds deep immutability; a mutable field in __hash__ breaks the dict
Coarse (subset of deps)highsilent wrong answers
Complete (all deps)lower; key build costs O(deps)correct

Value-based keys buy hit rate but require the hashed fields to be frozen for the object's lifetime. If a field in __hash__ changes after insertion, the entry sits in the wrong bucket and lookups miss or return a neighbour.

Failure modes and detection. Stale results from an incomplete key show up as order-dependent output: same inputs, different answers depending on call sequence. cache_info() on an lru_cache-wrapped function reports hits, misses, maxsize, currsize: a currsize that tracks distinct instances is the leak signature for functools.cache, which is unbounded. Detect the stale case by calling the function twice with a mutation between and asserting the second result changes.

When not to memoise. If the result genuinely depends on mutable state, pass that state as an argument so it enters the key, or drop the cache. Widening the key until it is complete is not free: a key that hashes the whole object on every call can cost more than the computation it saves.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-23

How does verifying against brute force interact with rollback, and where do people ignore that?

Answer

Core answer. Rollback structures (rollback DSU, rollback Mo's, DFS-based offline dynamic connectivity) are stateful and order-dependent: correctness is a property of the whole operation sequence, not of any single query. So brute-force verification has to replay the same sequence, and comparing final answers is not enough. The most common rollback bugs leave every answer correct and only corrupt the state that later operations read. That's the part people skip.

Mechanism. Rollback DSU: union by size, no path compression (find must be pure, if it mutates parent there is nothing to undo), and a history stack.

Python
parent = list(range(n)); size = [1]*n; history = []

def find(x):
    while parent[x] != x:
        x = parent[x]
    return x

def union(a, b):
    a, b = find(a), find(b)
    if a == b:
        history.append(None); return False
    if size[a] < size[b]:
        a, b = b, a
    parent[b] = a
    size[a] += size[b]
    history.append((b, a, size[b]))
    return True

def rollback():
    rec = history.pop()
    if rec is None: return
    b, a, sb = rec
    parent[b] = b
    size[a] -= sb

Trace n=4, ops union(0,1), union(2,3), union(1,3), rollback(), then find(1) vs find(3):

  • union(0,1): parent=[0,0,2,3], size=[2,1,1,1], history=[(1,0,1)]
  • union(2,3): parent=[0,0,2,2], size=[2,1,2,1], history=[(1,0,1),(3,2,1)]
  • union(1,3): find(1)=0, find(3)=2, sizes 2 vs 2 → parent=[0,0,0,2], size=[4,1,1,1], history=[...,(2,0,2)]
  • rollback(): parent[2]=2, size[0]=4-2=2 → parent=[0,0,2,2], size=[2,1,2,1]
  • find(1)=0, find(3)=2 → separate. Correct.

Now drop size[a] -= sb. Every answer above is still right: find only reads parent. But size[0] stays 4, so the next union(1,3) picks root 0 again and size[0] climbs to 6, then 8. Union-by-size stops bounding depth, and rollback Mo's degrades from O((n+q)√n · α) toward O((n+q)√n · n) worst case on adversarial input. A brute force that compares answers never sees it.

Two defect classes.

DefectAnswers change?Caught by answer comparison?
parent[b] not restoredyesonly if brute force replays the sequence
size[a] not decrementednonever
history popped FIFO instead of LIFOyesonly if rollback is actually triggered
find() does path compressionno, until rollbacknever

Where people ignore it.

  • Brute force recomputes each query from scratch. It never calls rollback, so the rollback path has zero coverage. The reference must apply the same incremental ops and undo them the same way.
  • Comparing only final output. Assert the invariant instead: after every rollback, len(history) equals the depth before the block, and size[root] equals the number of nodes reachable from it.
  • Random tests where rollback is rare. If all queries land in one Mo's block, rollback never fires. Force it: assert rollback count > 0, or generate sequences that alternate add and rollback.
  • Assuming the answer is the contract. For rollback structures the contract is state restoration plus the amortized bound; both need their own check.

Trade-off. Recompute-from-scratch brute force is trivial to write and catches answer-level bugs; replay-based brute force plus invariant assertions is more work but is the only thing that catches the state bugs. Run both: the first as a fast oracle, the second with forced rollback density.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-24

What would you ask a candidate who recites numeric overflow in counting problems but cannot apply it?

Answer

The question I'd ask is small, then extended twice.

Opening question. "Count the monotone lattice paths from (0,0) to (n,n) modulo 1e9+7, n up to 10^5. Write the recurrence and tell me exactly where the modulus goes."

A reciter writes dp[i][j] = dp[i-1][j] + dp[i][j-1] and says "take the mod at the end." An applier writes % MOD inside the loop and can say why.

Why it discriminates: the trace. Take the 1-D version, dp[i] = dp[i-1] + dp[i-2], dp[0] = dp[1] = 1, in C with long long. The values are Fibonacci numbers. F(92) = 7,540,113,804,746,346,429 fits in a signed 64-bit (max 9,223,372,036,854,775,807). F(93) = 12,200,160,415,121,876,738 does not. On two's-complement hardware it wraps to 12,200,160,415,121,876,738 − 2^64 = −6,246,583,658,587,674,878 (signed overflow is undefined behaviour in C, so that is what you observe, not what the standard promises). Every later term is now built on a wrong value, and the final % MOD returns a wrong answer. Reducing at each step never exceeds MOD + MOD before the reduction, so it cannot overflow.

Follow-up 1: subtraction. "Now the recurrence is dp[i] = dp[i-1] - dp[i-2]. What changes?" In C, Java and Go, (a - b) % MOD is negative when a < b: (3 - 5) % 1000000007 == -2. You write ((a - b) % MOD + MOD) % MOD. In Python (3 - 5) % 1000000007 == 1000000005 already, because Python's % follows the divisor's sign. A candidate who has only ever written Python misses this, and it is the most common wrong-answer bug in these problems.

Follow-up 2, where mod-every-step is wrong. "The answer needs dp[i] / 2 at each step, and the modulus is 1e9+7." Reducing early is now wrong unless you multiply by the modular inverse of 2, which exists only because 1e9+7 is prime. If the modulus were composite, or the divisor shared a factor with the modulus, you cannot invert: you carry exact big integers or restructure the recurrence. That is the trade-off: mod-every-step is cheap and correct for +, − and ×; it is not free for ÷.

What I listen for. The candidate names the mechanism (fixed-width wrap), gives the bound (for 1e9+7, MOD² ≈ 1e18 fits in 64 bits, so one multiply before reduction is safe), and knows the subtraction and division exceptions. Someone who says "just mod at the end" has memorised the phrase; someone who says "mod at the end overflows at F(93)" has the model.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-19

How would you review a pull request whose risk is state-space explosion?

Answer

I'd start by asking the author to write the state as a tuple with each dimension's bound taken from the problem's stated constraints, then do the multiplication myself. State-space explosion is a sizing bug, not a style bug, so the review is arithmetic first: cells = product of domain sizes; memory = cells × entry size; time = cells × transition cost. If that doesn't fit the budget, the PR doesn't merge as written: the fix is a smaller state, not a bigger machine. If it fits, I still want the author to have shown the state is minimal.

Four things I ask for before approving:

  1. The state, with bounds cited. Not dp[i][w][f] but "i ∈ [0, n], n ≤ 2000; w ∈ [0, W], W ≤ 2000; f ∈ {0,1}". If a bound isn't in the problem statement, the author is guessing and the sizing is unverifiable.
  2. The size arithmetic, in the PR description or a test. A one-line assertion beats a paragraph.
  3. A minimality argument. Two states with the same key must have identical feasible completions. If a dimension is a function of the others, it's redundant and should go.
  4. A test at the constraint boundary, plus a memory measurement. Correctness on the samples says nothing about the max input.

The arithmetic is usually where the PR dies:

statecellsint64
(i, w)2000 × 2000 = 4×10⁶32 MB
(i, w, coupon)8×10⁶64 MB
(i, w, coupon, category ∈ 1000)8×10⁹64 GB

The third row is the shape of the bug: each dimension the author adds to fix a wrong answer multiplies the table, and the multiplication is invisible in the diff.

Python
n, W = 2000, 2000
cells = n * W * 2
print(cells, cells * 8 / 2**20)   # 8000000 61.03515625

61 MiB is fine. The same state rolled to two rows is 2 × 2000 × 8 = 32 KB, because the recurrence only reads row i-1. That's a review comment worth making even when the full table fits: it converts a memory question into a time question, and time is cells × transition cost. A state count that fits can still blow the time budget if each state loops over a dimension: O(cells × K) is the other half of the explosion.

The minimality check is where I've caught the most. A PR had dp[r][c][k] for a grid with right/down moves only, R = C = 1000, k = steps taken. But after k moves you are at r + c = k, so k is a function of (r, c): 10⁹ cells declared, 10⁶ reachable, and the third dimension carries no information. Dropping it is a 1000× reduction with no change to the recurrence.

Merge criteria, then: the state count times the entry size fits the budget with headroom; the state is minimal, or the author has argued why the extra dimension is needed; there's a boundary test and a measured peak RSS. If the state is genuinely minimal and still too large, that's not a review comment: it's a design conversation, because the algorithm is wrong for the constraints and the fix is a different formulation, not more RAM.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-18

What belongs in a runbook section on pseudo-polynomial complexity, and what does not?

Answer

What a strong candidate says first

A runbook is read by whoever is on call, at 3am, with no context on the service. That fixes the inclusion test: a line earns its place only if it changes an action someone takes during an incident. By that test the section carries the numeric threshold at which the DP table stops fitting, the symptom that threshold produces, the knob that moves it, and the signal that tells you you are there. It does not carry the definition of pseudo-polynomial, the encoding-length argument, or the NP-hardness reduction: an on-call engineer cannot act on any of them.

Belongs in the runbookDoes not belong
The capacity W at which the table exceeds the memory budget, as a numberThe proof that W is exponential in its encoding length
The symptom: OOM kill, or p99 latency climbing with request payload size"The problem is NP-hard"
The knob: cap W, reject the request, or switch to the FPTASThe definition of pseudo-polynomial
The detection signal: table cells allocated, or W logged per requestThe reduction from subset-sum
The mitigation and what it costsThe taxonomy of complexity classes

Where the table actually blows up

The DP is n rows by W columns; with a rolling array, memory is O(W) and time is O(nW). Take int64 cells at 8 bytes (figures illustrative: measure on your own hardware):

  • n = 200, W = 10^5: 800 KB, 2×10^7 updates. Sub-second.
  • n = 200, W = 10^7: 80 MB, 2×10^9 updates. Seconds to a minute.
  • n = 200, W = 10^9: 8 GB, 2×10^11 updates. OOM, or minutes if it survives.

So the runbook line is "W above 10^7 with n in the hundreds exceeds the 1 GB container limit": a number, not a concept.

How the section fails

Two ways. Include the theory and the runbook grows past what anyone reads; the on-call engineer greps for "OOM" and lands in a paragraph about encoding lengths. Exclude the threshold and the first incident is spent rediscovering it: the pod OOMs, nobody knows W is the knob, and the fix is a config change nobody knows exists. Detect it by logging W per request and alerting on the 99th percentile crossing the threshold, not the mean: the mean hides the tail that kills the pod.

When capping is not enough

If W is genuinely unbounded, capping it is a product decision, not an engineering one, and the runbook should say so rather than pretend otherwise. The alternatives: cap and reject (cheap, changes semantics), an FPTAS with a stated ε (polynomial in n and 1/ε, gives up exactness), branch-and-bound (fast on typical instances, worst case unchanged), or shard the table across workers (buys memory, not time). The deciding criterion is whether the answer must be exact and whether the domain bounds W: a capacity in cents for a $10,000 limit is 10^6, which is fine; a capacity in bytes for a 1 TB volume is 10^12, which is not.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-17

How should on-call treat an alert that names the complexity of a dynamic program as the cause?

Answer

Treat the complexity named in the alert as a hypothesis the alert author wrote down, not as the diagnosis. Your first move is to confirm the symptom and find what changed; the asymptotic claim only tells you which knob to look at first.

State the assumption: the alert is on a service whose cost is dominated by input shape. Sequence alignment, Viterbi decode, edit distance, knapsack pricing. In practice the complexity usually appears in the alert name or its runbook annotation (dp_align_p99_breach (O(n·m) model)), not as a metric the monitor computes. If the service is I/O-bound, the named cause is noise and you say so in the incident notes.

Triage, in order:

  1. Read the symptom, not the cause. What actually fired: p99 latency, CPU saturation, OOMKill, queue depth? The complexity line is a comment in the alert body.
  2. Diff the inputs. Production complexity blowups are almost always an input-shape change: a new customer, a raised max-length config, a batch-size bump. The code's asymptotics did not change; n did.
  3. Quantify against the real distribution. Pull the input-size histogram for the window, not the model's assumed range.

Worked arithmetic. An alignment service runs a DP that is O(n·m) with O(1) transitions. p99 is 180 ms at n = m = 500; the alert threshold is 1 s. A customer uploads 4000-residue sequences: (4000/500)² = 64×, so 180 ms × 64 ≈ 11.5 s. That is the page. The mitigation is a length cap or banded alignment, not a rewrite.

Same root cause, different symptom: O(n²) states at 8 bytes each. n = 4000 gives 16M states, 128 MB per in-flight request; 20 concurrent requests is 2.5 GB and an OOMKill. If the alert names time complexity but the box is dying on memory, the named cause is half right and the runbook is misleading.

Alert on cause (complexity model)Alert on symptom (SLO burn)
Fires wheninput shape crosses the model's thresholduser-visible latency or errors degrade
Localizesfast, if the model is rightslow, needs a second step
Wrong whenconstant factors, cache effects, downstream stallsrarely wrong, just uninformative
Use whenthe DP is the only tenant and input shape dominatesshared service, many possible causes

Failure modes to name out loud:

  • Anchoring. You profile the DP for twenty minutes while the real cause is a downstream stall and the DP is just the caller blocked on it. Detection: the DP's own CPU time is flat while wall time climbs.
  • Stale model. Someone added a gap-penalty loop over the transition, the cost is now O(k) per state, and the alert still says O(n²). Detection: measured time scales with k, not with n².
  • Constant factors. O(n²) with a 40× constant blows a 1 s budget at n = 200 while the model says there is headroom.

What to do with the rule itself: an alert that names a cause will be wrong the next time it fires. Alert on the symptom (latency SLO burn, OOMKill rate) and move the complexity analysis into the runbook, where it can be wrong without misdirecting the page.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-21

How would you brief product on why recursion limits in top-down solutions delays a ship date?

Answer

The 90-second brief

"The feature works on our test files and fails on customer-sized ones. The algorithm calls itself once per row, and the runtime stops at 1,000 nested calls by default. A 10,000-row file hits that ceiling and the request errors out, not slow, failed. The fix is rewriting the core loop to iterate instead of recurse: two days of engineering, one day re-running the corpus. Or we cap uploads at 900 rows, ship Friday, and do the rewrite next sprint. Your call."

That structure is the whole answer: user-visible symptom, one number, two options with costs, one question back. Product does not need the word "recursion"; they need "fails above 1,000 rows" and "two days."

Why "just raise the limit" is not on the menu

CPython's default is sys.getrecursionlimit() == 1000. Raising it does not grow the C stack, so you trade a catchable RecursionError for a segfault that takes the worker process with it: no traceback, no per-request isolation, and it reads as an infrastructure problem. If someone proposes it in the room, that sentence ends the discussion.

The options, as product will ask for them

OptionCostWhat shipsRisk
Rewrite to bottom-up2 eng-days + 1 test-dayCorrect at any input sizeSlip 3 days
Cap input at 900 rows~2 hours (guard + clear error)Ships FridayBigger files get a rejection; support load
Raise recursion limit5 minutesNothing reliableSegfault under load; rejected

The code, so the estimate is checkable

Python
from functools import cache

def lis_top_down(a):
    @cache
    def best(i):
        return 1 + max((best(j) for j in range(i + 1, len(a)) if a[j] > a[i]), default=0)
    return max(best(i) for i in range(len(a)))

On a strictly increasing input, best(0) calls best(1) calls best(2) …, one frame per element, so len(a) == 10_000 means 10,000 frames against a 1,000 limit → RecursionError. On a decreasing input the same code never nests past one frame. That input-dependence is exactly why it survives testing.

The rewrite is mechanical:

Python
def lis_bottom_up(a):
    dp = [1] * len(a)
    for i in range(len(a) - 1, -1, -1):
        for j in range(i + 1, len(a)):
            if a[j] > a[i]:
                dp[i] = max(dp[i], 1 + dp[j])
    return max(dp, default=0)

Same recurrence, no call stack. On [3, 1, 2] it returns 2 (the subsequence 1, 2). Most of the two days is re-running existing fixtures against the new implementation, not writing it.

Why it hid until now

Fixtures are small. The failure needs an input whose dependency chain is proportional to its length, and a quick check uses ten rows, not ten thousand. Detection: a CI case that feeds the largest file in the corpus and asserts no RecursionError, plus a production guard that rejects oversized input with a 4xx naming the limit instead of letting it 500.

What not to say to product

Don't say "stack overflow": that reads as a crash in someone else's system. Don't say "it's a recursion problem" without the row count. Don't offer the rewrite without the number of days. One symptom, one number, two options, one question.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-22

What is the smallest experiment that would change your mind about greedy versus dynamic programming?

Answer

The smallest experiment is a differential test: implement greedy and an exact solver (DP or brute force) for small inputs, run them on a handful of random cases, and look for a mismatch. One counterexample is enough to change your mind. For coin change, the smallest counterexample is coins [1,3,4], target 6. Greedy picks 4, then 1, then 1: three coins. The optimal is 3+3: two coins. That single case proves greedy is not optimal for that coin system.

Why this is the smallest experiment: you don't need to prove greedy wrong in general; you just need one instance where it fails. The experiment is small because you can brute-force all combinations for small n. The cost is writing the exact solver, which is straightforward for coin change.

Python
def greedy(coins, target):
    coins = sorted(coins, reverse=True)
    count = 0
    for c in coins:
        while target >= c:
            target -= c
            count += 1
    return count if target == 0 else float('inf')

def dp(coins, target):
    INF = float('inf')
    dp = [0] + [INF] * target
    for i in range(1, target + 1):
        for c in coins:
            if c <= i and dp[i - c] + 1 < dp[i]:
                dp[i] = dp[i - c] + 1
    return dp[target]

coins = [1,3,4]
target = 6
print(greedy(coins, target))  # 3
print(dp(coins, target))      # 2

Trace for [1,3,4], target 6:

  • Greedy: sorted coins [4,3,1]. Take 4, remaining 2; take 1, remaining 1; take 1, remaining 0. Count = 3.
  • DP: dp[0]=0; dp[1]=1 (1); dp[2]=2 (1+1); dp[3]=1 (3); dp[4]=1 (4); dp[5]=2 (4+1); dp[6]=2 (3+3). So dp[6]=2.

Compare on small targets:

TargetGreedyDP
111
222
311
411
522
632

The mismatch at 6 is the signal. If you only tested targets 1–5, you'd wrongly conclude greedy is optimal. So the experiment must include enough small cases to catch the failure. For coin change, the smallest counterexample is at target 6. In general, the smallest experiment is to search for a counterexample up to some small bound, or to use a randomized differential test.

Trade-offs: Greedy is O(n log n) for sorting plus O(target/min_coin) for the loop; DP is O(target * len(coins)). For small targets, both are fast. The experiment is cheap. If you can't find a counterexample, you still need an exchange argument to be sure. The experiment is necessary but not sufficient for correctness. The failure mode is stopping too early: a few passing tests don't prove greedy works. The experiment changes your mind because it provides a concrete counterexample; without one, you're guessing.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-25

How would you document recognising a dynamic-programming problem so the next owner can operate it?

Answer

Core answer. Don't document "this is DP". Document the test that made you say so, in a decision record of about fifteen lines that lives next to the solution. Four fields, in this order: the trigger, the state in one sentence, the recurrence with its complexity, and the counter-signals. The cheaper formulations you rejected and the input that killed them. A next owner who can re-run that test can also tell when it stops holding, which is the part a // DP comment never gives them.

Why DP was the right call. Two properties have to hold, and the record should say which one you actually checked. Overlapping subproblems: the same state is reached by many paths, so memoising it turns exponential recursion into a polynomial table. Optimal substructure: an optimal answer for the whole is composed from optimal answers for the sub-states, so you can fill bottom-up instead of enumerating. Edit distance has both: state (i, j) is reached from three neighbours, and the best alignment of the first i and j characters is built from the best alignments of shorter prefixes.

The record, filled in. For edit distance:

trigger:    minimum edits over a sequence of character decisions
state:      dp[i][j] = edit distance between source[:i] and target[:j]
recurrence: dp[i][j] = dp[i-1][j-1]                        if chars match
                       else 1 + min(dp[i-1][j], dp[i][j-1], dp[i-1][j-1])
base:       dp[0][j] = j, dp[i][0] = i
cost:       O(m*n) time, O(min(m,n)) space with two rolling rows
rejected:   greedy positional substitution — gives 3 on "abc" -> "bcd",
            optimal is 2 (delete 'a', append 'd')

The trace that makes the recurrence checkable, "cat" -> "cut":

        ""   c   u   t
 ""      0   1   2   3
 c       1   0   1   2
 a       2   1   1   2
 t       3   2   2   1

dp[3][3] = 1: one substitution. Every cell is min of its three neighbours plus the match/mismatch term, so a reader can recompute any entry by hand.

Signals, with the problems that pin them down.

SignalNamed problemStateCost
Count or optimum over a sequence of decisions0/1 knapsackdp[w] = best value at capacity wO(nW) time, O(W) space
Two sequences compared position by positionLCS, edit distancedp[i][j] over prefixesO(mn) time
Enumerate every configurationN-Queens—backtracking, O(n!)
Provable local ruleinterval scheduling—greedy, O(n log n)

Failure modes the next owner has to detect. First, DP applied where the state is never reused: instrument the memo and watch the hit rate. If every lookup misses, the recursion tree is a path and the table is dead weight: plain recursion was correct. Second, greedy was actually correct: the rejected field must carry the counter-example that killed it. If it can't, greedy wasn't ruled out. Third, the cost note is load-bearing: knapsack's O(nW) is pseudo-polynomial, so a capacity of 10^9 makes the table infeasible and the owner needs a different formulation, not a bigger array.

What to leave out. Don't restate the recurrence in prose, don't paste the whole solution, and don't write "this is DP because it's hard". The record is the test, not the answer.

Curated: · Written: · Reviewed:

Difficulty: Medium