Skip to content
Tech Interview Prep
Technical interview guide

Backtracking

Recursive brute-force search with early pruning: build a partial solution, and abandon it the moment it can't possibly work.

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

Scope: Language-neutral, with generator 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 backtracking as a search over a decision tree and how it changes a production decision.

Answer

Core answer

Backtracking is depth-first search over a tree of partial solutions. Each level of the tree fixes one decision; the search extends a partial candidate, recurses, then undoes the extension so one mutable state object serves every branch. The undo is the whole trick: without it, state from one branch leaks into its siblings and results become order-dependent.

The production decision it changes is whether a search-based feature ships at all, and with which engine. Backtracking is the right call when the decision tree is small after pruning and you need an exact answer. It is the wrong call when the tree is exponential and pruning cannot cut it, then you move to memoisation, a heuristic, or a solver.

Mechanism

The skeleton is three lines: choose, explore, unchoose.

Python
def solve(state, level):                 # Python 3.12
    if level == n:
        return [state.copy()]            # complete candidate
    out = []
    for choice in candidates(state, level):
        state.append(choice)             # choose
        out += solve(state, level + 1)   # explore
        state.pop()                      # unchoose
    return out

Worst case is O(b^d) time for branching factor b and depth d, with O(d) stack. Pruning is what turns that bound into a budget: a constraint checked at each level removes whole subtrees, so the number you measure is nodes visited, not b^d.

Trace: 4-queens, one queen per row, reject any column that attacks an earlier queen:

rowsurviving partial placementscount
0(0),(1),(2),(3)4
1(0,2),(0,3),(1,3),(2,0),(3,0),(3,1)6
2(0,3,1),(1,3,0),(2,0,3),(3,0,2)4
3(1,3,0,2),(2,0,3,1)2

16 nodes visited, 2 solutions. The unpruned tree is 4+16+64+256 = 340 nodes, so pruning cut it ~21×, and the cut grows with n.

Trade-offs

approachwins whencost
backtracking + pruningexact answer, small pruned tree, cheap constraint checksexponential worst case; returns first solution found, not the best
memoised DPthe same partial state is reachable many waysneeds a hashable state; O(states) memory
greedy / local searchhuge space, approximate answer acceptableno exactness, can stall in local optima
SAT / CP-SAT solverlarge space, need optimality or a proofdependency, encoding cost, non-trivial latency

Deciding criterion: if the same partial state is reachable by many paths, memoise; if the space is exponential and pruning cannot cut it, a solver's clause learning beats hand-rolled backtracking.

Failure modes

  • Exponential blowup: no pruning or weak pruning → timeout. Detect by logging nodes visited per request; if it tracks b^d, pruning is not firing. Fix with forward checking or constraint propagation.
  • Stack depth: recursion depth equals d, and Python's default limit is 1000 (sys.getrecursionlimit()), so d near that raises RecursionError. Convert to an explicit stack.
  • State leak: a missed undo makes results order-dependent. The same input gives different answers on repeated runs. Detect by running the same input twice and diffing.
  • No optimality: backtracking returns the first complete candidate, not the cheapest. If you need the minimum, search all or add branch-and-bound with a bound.

The production decision

Concretely: a dependency resolver that backtracks over version choices. Suppose a real lockfile gives b≈10 and d≈20 (hypothetical figures); b^d is 10^20, and no pruning survives that, so the decision is to move to a CP-SAT solver with conflict-driven clause learning, or to bound the search with a timeout and fall back to a heuristic. If the pruned tree stays in the thousands of nodes, keep the backtracking search: it is exact, dependency-free, and its cost is measurable. The number that decides it is p99 nodes visited on real lockfiles: instrument it before choosing.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-3

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

Answer

Clarify first. "The base case" only means something once you name the recursion. I'll take the one interviewers actually use it for: recursive enumeration, generating subsets and permutations, because that is where the base case is most often wrong. The same distinction carries to any recursion: the base case is the condition that says the current partial candidate is a complete answer, and that is not always the same as there are no choices left.

The answer. Two termination conditions get conflated:

  1. No remaining choices: structural. In permutations, i == n; in the loop-based subset generator, the for range is empty.
  2. Candidate is complete: semantic. A permutation is complete at length n. A subset is complete at every node, including the empty one.

For permutations these coincide: you reach a full-length arrangement exactly when no choices remain, so recording at leaves is correct. For subsets they do not: every node is a valid subset, so recording only at leaves throws away most of the answer.

Python
def subsets(a, i, cur, out):
    out.append(cur[:])          # every node is a complete subset
    for j in range(i, len(a)):
        cur.append(a[j])
        subsets(a, j + 1, cur, out)
        cur.pop()

out = []
subsets([1, 2], 0, [], out)
print(out)   # [[], [1], [1, 2], [2]]

Trace, in call order: the root appends []; j=0 pushes 1, the child appends [1], its j=1 pushes 2, the grandchild appends [1, 2], its loop range is empty, pop 2; pop 1; j=1 pushes 2, that child appends [2], loop empty, pop 2. Four results, and the empty subset is one of them.

Three shapes of base case.

ShapeConditionExampleRecords at
Structuralno choices leftpermutationsleaves
Every nodealways trueall subsetsevery call
Predicate on stateaccumulated value hits targetcombination sumwherever remaining == 0

Combination sum breaks both structural rules: you record when remaining == 0 and prune when remaining < 0, which is neither a leaf nor every node.

Where it goes wrong.

  • Recording only at leaves for subsets. For n = 3 the recursion tree has 4 leaves but 8 subsets. You emit [1,2,3], [1,3], [2,3], [3] and lose [], [1], [2], [1,2]. Detect it with assert len(out) == 2 ** n on a small input; eyeballing the output does not catch a missing subset.
  • Recording at every node for permutations. Permutations of [1,2,3] would emit 1 + 3 + 6 + 6 = 16 results instead of 6. Assert len(out) == factorial(n).
  • Appending cur instead of cur[:]. Every entry aliases the same list, which is empty after the final backtrack, so out becomes [[], [], [], []]. Detect it by checking the results are not all identical.
  • Off-by-one in the structural check. if i > len(a) instead of == indexes past the end; if i == len(a) - 1 drops the last element from every result.

Deciding. Ask whether the answer set is closed under taking prefixes. If yes (subsets), record at every node. If no (permutations), record at leaves. If the answer is defined by a value rather than a shape (combination sum), record on the predicate and prune on its complement. The base case is a property of the problem's answer set, not of the recursion's shape, which is why "stop when there are no choices left" is a slogan rather than a rule.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-2

How would you reason about the choose-explore-unchoose shape in a system you own?

Answer

I'd treat choose-explore-unchoose as a state-restoration contract and pin it to a system before saying anything else. Take a shift scheduler I own: 40 shifts, 12 nurses, one nurse per shift, no nurse on consecutive shifts, no nurse over 5 shifts. Search state is two mutable arrays (assignment[40] (nurse per shift, -1 unfilled) and nurse_load[12]) recursed over candidate nurses per shift.

The contract is one sentence: at every node, state on entry equals state on exit. Choose mutates, explore recurses, unchoose is the exact inverse of choose. Branch independence, the solution set not depending on candidate order, follows from that invariant; it isn't a separate rule. If unchoose is the true inverse, siblings start from identical state and order can't matter.

Alternatives, and when each wins:

ApproachCost per nodeCorrectness riskUse when
Mutate + undoO(1)undo must be the exact inversestate small, inverse cheap (the scheduler)
Copy-on-recurseO(state)none by constructionstate tiny, or the inverse is hard to write
Trail / checkpointO(delta)rollback to a marked depthneed to undo to an arbitrary earlier point (CP solvers)

Scheduler state is 52 ints, so copy-on-recurse is ~208 bytes per node and survives 40 levels of depth; I keep mutate-and-undo because the inverse is trivial and the node count is large.

The failure is specific. Suppose choose does nurse_load[v] += 1 but unchoose forgets the decrement. Trace 3 shifts, 3 nurses, max 1 shift each: 6 valid permutations. Loads start {A:0, B:0, C:0}.

  • S0=A → load[A]=1. S1=A rejected. S1=B → load[B]=1. S2=A and S2=B rejected; S2=C → load[C]=1, record A,B,C. No decrements on unwind, so loads stay {A:1, B:1, C:1}.
  • Back at S1, C is now rejected (load[C]=1). Unchoose S0=A leaves loads unchanged.
  • S0=B → load[B]=2, loads {A:1, B:2, C:1}. S1: A, B, C all rejected. Dead end.
  • S0=C → load[C]=2, loads {A:1, B:2, C:2}. S1: all rejected. Dead end.

One solution instead of six. The bug is invisible on the first branch; it only surfaces when a sibling re-enters with stale load.

Detection: after search(...) returns, assert nurse_load == snapshot taken before the call. That catches a missing inverse at the exact node. Then run the whole search with candidate order shuffled and compare solution sets; a set that shrinks under reordering is the signature. Finally, count solutions against brute force on small inputs: 1 vs 6 is a gap a unit test catches immediately.

When not to use it: if state is large or the inverse is error-prone (mutating a hash map with deletions), copy-on-recurse or a persistent structure removes the whole bug class; if you need to roll back to an arbitrary earlier point, a trail with depth markers beats hand-written inverses.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-4

What does pruning is the whole point guarantee, and what does it deliberately leave open?

Answer

The guarantee. Pruning guarantees the search stays exact: it returns the same solution set as exhaustive enumeration. That is two halves, and both are required. Soundness: every candidate the search accepts is a real solution, because acceptance is still checked against the full constraint set. Completeness: no solution is lost, because a prune fires only on a partial candidate that provably cannot be extended to a solution. The second half is the load-bearing one, and it holds only if the prune test is a valid necessary condition: it rejects a partial assignment only when every completion of that assignment violates some constraint. A prune that is merely a good guess (a heuristic bound, a "this looks bad" cutoff) breaks completeness and turns exact search into a heuristic that can silently miss the optimum.

What it leaves open. Cost. Pruning says nothing about how much of the tree actually gets cut, and therefore nothing about runtime. The speedup is a property of the instance, the tightness of the prune, and the order in which you branch, not of pruning itself. A prune that fires on every node and one that fires on none are both "correct pruning"; they differ by orders of magnitude in nodes visited. Worst case stays exponential: if the constraint only bites near the leaf, early pruning cuts almost nothing.

Trace. The same solver, run with and without the prune, counting every placement made:

Python
def search(n, prune):
    nodes = 0
    def valid(qs):
        return all(qs[i][1] != qs[j][1] and
                   abs(qs[i][1] - qs[j][1]) != abs(qs[i][0] - qs[j][0])
                   for i in range(len(qs)) for j in range(i + 1, len(qs)))
    def place(col, qs):
        nonlocal nodes
        if col == n:
            return 1 if valid(qs) else 0
        found = 0
        for row in range(n):
            if prune and any(row == r or abs(row - r) == col - c
                             for c, r in qs):
                continue
            nodes += 1
            found += place(col + 1, qs + [(col, row)])
        return found
    sols = place(0, [])
    return nodes, sols

search(4, False)   # (340, 2)
search(4, True)    # (16, 2)

Both return the same 2 solutions; the pruned run visits 16 nodes against 340. The same code on n=8 gives the classic figures: 16,777,216 leaf placements versus 2,057 pruned nodes. The guarantee is identical in both runs. Only the cost moved.

Alternatives, and when not to prune. Forward checking and arc consistency (AC-3) propagate constraints into the domains of unassigned variables, so they prune whole domains rather than one branch: stronger per node, more expensive per node. Branch and bound prunes on a bound instead of feasibility, and requires that bound to be admissible (never optimistic past the true optimum) or optimality is lost. Variable and value ordering (MRV, degree heuristic, least-constraining value) does not prune at all; it changes how fast the existing prune fires. Memoisation over subproblems replaces the tree with a DAG.

The deciding criterion is the cost of the prune test against the size of the subtree it removes. A test costing O(k) that removes a subtree of size s pays for itself when s ≫ k. Do not prune when the test is near-full constraint propagation on a shallow tree: you spend more checking than you save; when you need all solutions and the prune is only valid for existence; or when you cannot prove the necessary condition, in which case it is a heuristic and must be labelled one.

Failure modes. An unsound prune misses solutions: catch it by cross-checking against brute force on small n. A weak prune is correct but buys nothing: count nodes; if pruned nodes track exhaustive nodes, the constraint is not biting early. An expensive prune drops node count while wall time rises: profile time per node, not just nodes.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-7

Where does generating subsets matter, and where is it irrelevant?

Answer

Short version: subset generation matters when the deliverable is a set of subsets. Feature selection, frequent-itemset mining, combinatorial test coverage, bitmask DP. It is irrelevant when you need a count (closed form 2^n), an extremum (DP or greedy), or when pruning structure collapses the search before you enumerate anything.

Mechanism. Each of the n elements is one binary decision: include or exclude. The recursion tree has 2^n leaves, and every node on the way down is already a valid subset, which is why you can emit at each node instead of only at the leaves. Enumerating {a,b,c} by counting bitmasks 0..7:

000 -> {}        100 -> {c}
001 -> {a}       101 -> {a,c}
010 -> {b}       110 -> {b,c}
011 -> {a,b}     111 -> {a,b,c}

That is the whole algorithm, and it is also the whole cost: the output has 2^n members, so no method beats 2^n. The bound is output-sensitive, not a property of the loop.

nsubsets 2^nat 10^7 subsets/s
201,048,576~0.1 s
301.07 x 10^9~107 s
401.1 x 10^12~30 h

Where it matters. Feature selection over n candidate features is a search over 2^n subsets; at n=30 that is 10^9 models, so people fall back to forward selection or L1. Held-Karp for TSP is DP over subsets, O(2^n · n^2): n=20 is ~4x10^8 operations and runs; n=25 is ~2x10^10 and does not. Frequent-itemset mining (Apriori) and combinatorial test coverage both enumerate subsets of items or parameter values.

Where it is irrelevant. If the caller wants the count, it is 2^n: no enumeration. If they want the maximum subset sum under a weight cap, that is knapsack DP in O(n·W), not 2^n. If feasible sets form a matroid, greedy is provably optimal and enumeration is wasted. Apriori never touches all 2^n subsets because downward closure prunes: if {A,B} is infrequent, every superset is too.

Failure mode. Treating enumeration as cheap because the loop is O(1) per step. Detection: compute 2^n and the expected output size before running, and log subsets emitted per second. A job that looks fine at n=20 stalls at n=30 and OOMs at n=35 if you materialise the list instead of streaming.

Deciding criteria. Ask three things: is the answer a set of subsets (enumerate), a number (closed form or DP), or an optimum with structure (greedy/DP)? Does monotonicity or a matroid let you prune? Can you stream rather than store? If none of those apply and n is past ~25, the honest answer is that exact enumeration is off the table and you need a heuristic.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-8

Teach generating permutations to an engineer who has only seen it as a rule of thumb.

Answer

Core answer (first 90 seconds). A permutation is one of the n! orderings of n distinct items. Generate them by backtracking: fill position 0 with any unused element, recurse to fill the rest, then undo the choice and try the next. The count is n!, so settle first whether n is small enough: for n ≥ 12 you are usually looking at the wrong algorithm, not a slow one. If order must be lexicographic or the input has duplicates, sort first and skip equal siblings. If you only need to consume them, yield lazily instead of building a list.

The generator.

Python
# Python 3.12
def permutations(items):
    items = sorted(items)          # lexicographic order; also groups duplicates
    n = len(items)
    used = [False] * n
    path = []
    def rec():
        if len(path) == n:
            yield tuple(path)
            return
        for i in range(n):
            if used[i]:
                continue
            if i > 0 and items[i] == items[i-1] and not used[i-1]:
                continue           # skip duplicate siblings
            used[i] = True
            path.append(items[i])
            yield from rec()
            path.pop()
            used[i] = False
    yield from rec()

Trace on [1, 2, 3]. rec picks index 0 → path [1]; index 1 → [1,2]; index 2 → [1,2,3], yield. Undo to [1,2], no indices left, undo to [1]; pick index 2 → [1,3]; index 1 → [1,3,2], yield. Undo to []; pick index 1 → [2]; index 0 → [2,1]; index 2 → [2,1,3], yield. Continuing the same undo-and-advance gives the yields in order: (1,2,3), (1,3,2), (2,1,3), (2,3,1), (3,1,2), (3,2,1).

The n! wall, with arithmetic. A tuple of n small ints is roughly 40 bytes of header plus 8 bytes per slot on CPython; add 8 bytes for the list slot. At ~130 bytes per 11-element tuple:

nn!materialised at ~130 B each
103,628,800~0.5 GB
1139,916,800~5 GB
12479,001,600~62 GB
136,227,020,800~810 GB

A lazy generator holds O(n) memory but still takes n! time, so streaming buys memory, not feasibility.

Trade-offs. The used-marker version above costs O(n) extra space, emits lexicographic order when you iterate indices in order, and handles duplicates with one skip. An in-place swap version costs O(1) extra space but its output order is not lexicographic and duplicates need a set or sort-and-skip. Heap's algorithm does exactly one swap per permutation with O(n) space: it wins when the per-permutation work is expensive and you want to mutate incrementally rather than rebuild, but it is not lexicographic. std::next_permutation (C++) and itertools.permutations (Python) are the right tools when you need the k-th permutation, a prefix, or early exit: next_permutation is O(n) per call, lexicographic, and duplicate-safe.

Failure modes. n! blowup: detect by counting before coding. Duplicates producing repeated output: detect when len(set(result)) < n!. Recursion depth n: fine to ~1000 in CPython, then go iterative. Materialising when you only need to stream: detect by watching RSS climb linearly with yield count.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-10

Why does combination generation thread a start index through the recursion instead of tracking used elements the way permutation code does?

Answer

A combination is a set, so the order in which you pick its members is a symmetry: [A,B] and [B,A] must not both come out. The start index is that canonical-order rule made structural: every index on the path is smaller than any index still available, so each subset is emitted exactly once, in ascending input order.

Mechanically, dfs(start) means "everything at or after start is still available". You pick index i and recurse at i + 1, so an element can never be taken twice and a used array would be redundant.

Python
def combinations(a, k):
    n, out, path = len(a), [], []
    def dfs(start):
        need = k - len(path)
        if need == 0:
            out.append("".join(path)); return
        if n - start < need:                  # not enough left to finish
            return
        for i in range(start, n - need + 1):  # leave room for `need` picks
            path.append(a[i])
            dfs(i + 1)                        # next level may only go right
            path.pop()
    dfs(0)
    return out

combinations("ABCD", 2)
# ['AB', 'AC', 'AD', 'BC', 'BD', 'CD']   ->  C(4,2) = 6

Trace n = 4, k = 2: at start = 0 pick A, then B/C/D give AB, AC, AD; pick B, then C/D give BC, BD; pick C, then D gives CD. Six leaves, each pair once, already in lexicographic order. itertools.combinations holds the same invariant in its iterative form: indices[j] = indices[j-1] + 1 keeps the chosen indices strictly increasing.

Permutations are a different shape. The depth of the tree is a slot in the output, not a position in the input, so at every level any unused element is fair game; that needs a used array, or an in-place swap whose undo is the backtracking step. There, [A,B] and [B,A] are two different answers. Give a permutation search a start index and you only ever emit the increasing ones: you have written combinations again.

Dropping the start index fails in two distinct ways depending on what replaces it:

choice at each levelleavesoutput
indices ≥ start, recurse at i + 1C(n,k)each combination once
any unused index (used array)P(n,k) = k!·C(n,k)each combination k! times
any index at alln^krepeats inside one combination

For n = 20, k = 10: 184,756 leaves versus 670,442,572,800 versus 10^13. The used-array version is not wrong, it just does 10! = 3,628,800 times the work and hands you duplicates that a later dedupe has to absorb: the factorial is paid before the fix runs.

The check is arithmetic, not eyeballing: assert len(result) == math.comb(n, k) on a small input and that every returned tuple is strictly increasing in input position. One thing the start index does not give you is distinct combinations when the input holds duplicate values; that still needs a same-level skip of equal values.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-9

The input array can contain duplicate values. How do you generate all subsets without producing duplicate subsets?

Answer

Assume the input is an array where equal values at different indices are indistinguishable, each element is used at most once, and the caller wants every distinct subset of values exactly once. That is a multiset-subsets problem, not element reuse.

The rule: sort the input first, then at each recursion depth take a value only if it is the first of its equal run at that depth. Sorting turns 'are these two values equal' into 'are these two values adjacent', so the check is one comparison against nums[i-1] and costs nothing measurable next to the output.

Why naive enumeration duplicates: the tree branches per index, not per value. With [2, 2] the leaf {2} is reached twice, take index 0 or take index 1, and with [1, 2, 2] the subset {1, 2} has two paths. 2^n leaves, but only the product of (count + 1) over distinct values is required output.

inputleaves walkeddistinct subsets
[2, 2]43
[1, 2, 2]86
20 copies of one value1,048,57621
Python
# Python 3.14
def subsets_of_multiset(nums):
    nums.sort()
    out, path = [], []
    def dfs(start):
        out.append(path[:])
        for i in range(start, len(nums)):
            if i > start and nums[i] == nums[i - 1]:
                continue          # this equal value was already offered at this depth
            path.append(nums[i])
            dfs(i + 1)
            path.pop()
    dfs(0)
    return out

i > start is the whole correctness argument. When i == start, nums[i-1] is the element the parent level just chose, so the pair has to be allowed: [1, 2, 2] must emit [1, 2, 2]. When i > start, nums[i-1] was offered at this same depth and passed over, so taking its equal now would rebuild a subset an earlier branch already produced.

The include/exclude formulation says the same thing with a used flag, where used[i-1] means 'the previous equal value is in the current path':

Python
# Python 3.14 — per-element include/exclude over the sorted array
def dfs(i):
    if i == len(nums):
        out.append(path[:])
        return
    used[i] = False
    dfs(i + 1)                                    # exclude
    if not (i > 0 and nums[i] == nums[i - 1] and not used[i - 1]):
        path.append(nums[i]); used[i] = True
        dfs(i + 1)                                # include
        used[i] = False; path.pop()

If the previous equal value was excluded, including this one duplicates the branch that included the previous and excluded this one. The flag is cleared on un-choose: the rollback choose-explore-unchoose already owes you; forgetting to clear it emits phantom subsets.

The trap is deduplicating after the search. The naive run still walks all 2^n leaves and copies every path into a set: twenty identical values cost 1,048,576 leaves and path copies for 21 results. Worse, a post-hoc set makes a wrong algorithm pass its tests, so the broken skip check looks fine until someone asserts the outputs that are missing.

Contrast with plain subsets: with distinct values, 2^n leaves are 2^n required results, nothing can be pruned, and the skip condition is never true. The bug appears when the check is added without the sort (it compares unrelated neighbours and silently drops subsets) or written as i > 0 instead of i > start (same missing [1, 2, 2]). Library generators do not rescue you either: itertools.combinations and the documented powerset recipe operate on positions, so equal values at different indices still yield duplicate sets.

In practice: sort once, prune before emitting, quote the bound as the product of (count + 1) rather than 2^n, and make at least one test input contain a repeated value. [1, 2, 2] catches both wrong-skip bugs and a distinct-value test catches neither.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-15

How would you explain counting versus enumerating without using the usual slogan?

Answer

The slogan is "counting is easy, enumeration is hard", or its formal cousin, "counting is polynomial, enumeration is exponential." I'd drop it because it's false in both directions. The real distinction is simpler: counting asks for a number, enumeration asks for a witness set. That one difference decides the algorithm, and it is not a complexity class.

Why counting can collapse. Counting can merge partial solutions that will contribute the same number of completions. Two partial paths that reach the same cell are interchangeable for the count, so a DP keeps one number per cell instead of one path per cell. That merging is the whole trick: it's why counting paths, counting subsets with a property, or computing an optimum can be polynomial when the objects themselves are exponential in number.

Why counting is not always easy. Merging only works when the structure lets you. Counting perfect matchings in a bipartite graph is the permanent of its adjacency matrix, and that is #P-complete (Valiant, 1979). Counting satisfying assignments of a 3-CNF is #P-complete for the same reason. So "counting is polynomial" is a claim about the problem, not about counting.

Why enumeration is not always hard. Enumeration is bounded below by the output size, you must emit every object, but that's a floor, not an exponential. Polynomial-delay enumeration (Johnson, Papadimitriou, Yannakakis, 1988) emits each next solution in time polynomial in the input, so total cost tracks the number of solutions, not the size of the search space. If the output is small, enumeration is cheap even when the space is huge.

The deciding questions. Three, in order:

  1. Does the consumer need the objects, or only a number or an optimum? If only a number, look for aggregation before you write a search.
  2. Does the structure let partial solutions merge? If yes, DP, inclusion–exclusion, or linearity of expectation gives you a polynomial count.
  3. Is the output itself exponential? If yes, enumeration is off the table no matter how clever the generator.

The failure this prevents. Enumerating in order to count. Grid paths make it concrete:

Python
from math import comb

def count_paths(m, n):
    # each path is (m-1) downs and (n-1) rights
    return comb(m + n - 2, m - 1)

count_paths(20, 20)   # 35345263800

Trace: m+n-2 = 38, m-1 = 19, C(38,19) = 35345263800. One arithmetic operation. A DFS that emits each path instead has 35,345,263,800 leaves; at a hypothetical 10^7 paths/second that is about 59 minutes, while the DP that fills a 20×20 table is 400 cells. Same answer, and the enumeration version is the one that times out.

ProblemCountingEnumerating
Grid paths, m=n=20C(38,19), O(1)3.5×10^10 outputs
Perfect matchings, bipartite#P-complete (permanent)output-sensitive
3-CNF satisfying assignments#P-completeoutput-sensitive

The failure survives casual testing because the happy path hides it: a small grid, a sparse instance, or a test that only checks the count's value never exercises the blow-up. It shows up the first time the input is large enough that the count is astronomically large but the DP is still instant.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-13

Given a 2D grid of characters and a target word, how do you search for a path of horizontally or vertically adjacent cells that spells the word without reusing a cell, and why must the mark be undone on the way back?

Answer

One cell may be used once per candidate path, not once for the whole search: the same cell has to be legal again for a different branch. So this is a depth-first walk where each frame consumes one character of the word, and the "used" state is pushed on the way down and popped on the way back. Assumptions: rectangular grid, four directions (no diagonals), word non-empty.

The mark brackets the recursive calls:

Python
DIRS = ((1, 0), (-1, 0), (0, 1), (0, -1))

def exist(board, word):
    R, C = len(board), len(board[0])
    used = set()

    def dfs(r, c, k):
        if k == len(word):
            return True
        if not (0 <= r < R and 0 <= c < C):
            return False
        if board[r][c] != word[k] or (r, c) in used:
            return False
        used.add((r, c))                     # choose
        found = False
        for dr, dc in DIRS:
            if dfs(r + dr, c + dc, k + 1):   # explore
                found = True
                break
        used.discard((r, c))                 # unchoose
        return found

    return any(dfs(r, c, 0) for r in range(R) for c in range(C))

Python 3.13.

The discard has to happen because after a branch fails, its cells belong to the next branch. On this board, "AABC" is a yes:

A A
B C

The attempt starting at (0,0) matches A, A and then stalls: from (0,1) the only unmarked neighbour is C. It backtracks and unmarks (0,1) and (0,0). The attempt starting at (0,1) then walks (0,1)→(0,0)→(1,0)→(1,1) and answers yes. If the first attempt had left its marks behind, the second would reject a legal cell and return a false negative. That is the whole undo step: the mark describes the current path, not the grid.

Cost: with L = len(word) on an R×C grid there are R·C start cells, and from the second character on at most 3 of the 4 neighbours are unmarked, so one start's tree is at most 4·3^(L-1) nodes. Worst case O(R·C·3^L) time, O(L) auxiliary space for the path and the used set. The bound is not decorative: a board full of A's against the word "AAA…AB" enumerates nearly every simple path before saying no. A yes short-circuits on the first path found; a no must exhaust the tree, so the negative answer is the expensive one. Filter first: if the word is longer than R·C or needs more of some letter than the board holds, answer no without searching, and start from whichever end of the word matches fewer cells.

Where the mark lives is a trade-off. Writing a sentinel into board[r][c] and restoring the original character is O(1) per node and avoids hashing an (r,c) tuple on every frame, which matters at 3^L. It also mutates input: an early return True or an exception skips the restore, and the next query over the same board is then wrong. Keep a separate visited structure when the board is shared or the search may be retried; mutate when you own the board and restore on every exit path.

Recursion depth is bounded by L, not R·C: each frame consumes one character. Python's default limit is 1000 (sys.getrecursionlimit), so a word near that length raises RecursionError; sys.setrecursionlimit can raise it, but the docs warn that a limit set too high can crash the interpreter, so for unbounded L rewrite the DFS with an explicit stack instead.

Many dictionary words on one grid: build a trie of the words and walk it from every cell in a single DFS, recording a word at each terminal node. The used set is still one per path, mark and unmark are unchanged and shared across words, and shared prefixes stop being recomputed: 1,000 words sharing "inter" cost one walk for that prefix. Prune the branch the moment the trie node has no child, and delete found words (dropping empty nodes) to stop early.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-25

How do you implement Word Search on a 2D grid using backtracking and in-place visited tracking?

Answer

Clarify two things before writing code. First, may the board be mutated? In-place marking is only legal if it may, and if the caller needs the board unchanged you must restore on every exit path, not just the failure path. Second, what is the alphabet? The sentinel trick needs a character that cannot appear in the input; on the usual LeetCode 79 limits the board and word are English letters, so "#" is safe.

Given that, the answer is: DFS from every cell, overwrite the current cell with the sentinel before recursing, restore it after. Time O(R·C·3^(L-1)), space O(L) stack frames and no visited set.

Mechanism

At each step (r, c) where board[r][c] == word[k]:

  1. If k == L - 1, the whole word matched: return True.
  2. Save original = board[r][c], set board[r][c] = "#".
  3. Recurse into the four orthogonal neighbours that are in bounds and not "#", with k + 1.
  4. Restore board[r][c] = original at a single exit point, then return whether any neighbour succeeded.
Python
def exist(board: list[list[str]], word: str) -> bool:
    if not board or not board[0] or not word:
        return False

    rows, cols = len(board), len(board[0])

    def dfs(r: int, c: int, k: int) -> bool:
        if board[r][c] != word[k]:
            return False
        if k == len(word) - 1:
            return True

        original, board[r][c] = board[r][c], "#"   # in-place visited mark
        found = False
        for dr, dc in ((-1, 0), (1, 0), (0, -1), (0, 1)):
            nr, nc = r + dr, c + dc
            if 0 <= nr < rows and 0 <= nc < cols and board[nr][nc] != "#":
                if dfs(nr, nc, k + 1):
                    found = True
                    break
        board[r][c] = original                      # single restore point
        return found

    for r in range(rows):
        for c in range(cols):
            if dfs(r, c, 0):
                return True
    return False

The board[nr][nc] != "#" test is redundant with the entry check, dfs would reject "#" anyway, but it skips a call frame per rejected neighbour, which is the hot path.

Trace

board = [['A','B','C','E'],
         ['S','F','C','S'],
         ['A','D','E','E']]
word  = "ABCCED"
callcellcharmarksneighbours tried
dfs(0,0,0)(0,0)A(0,0)=#(1,0)='S'≠'B' → False; (0,1)='B' → recurse
dfs(0,1,1)(0,1)B(0,1)=#(1,1)='F'≠'C' → False; (0,0)='#' skip; (0,2)='C' → recurse
dfs(0,2,2)(0,2)C(0,2)=#(1,2)='C' → recurse
dfs(1,2,3)(1,2)C(1,2)=#(0,2)='#' skip; (2,2)='E' → recurse
dfs(2,2,4)(2,2)E(2,2)=#(1,2)='#' skip; (2,1)='D' → recurse
dfs(2,1,5)(2,1)D—k == L-1 → True

Unwinding restores (2,2)→'E', (1,2)→'C', (0,2)→'C', (0,1)→'B', (0,0)→'A'. exist returns True with the board byte-identical to the input.

The rollback path matters just as much. With word = "ABCB": dfs(0,0,0) marks (0,0); (1,0)='S' fails; (0,1)='B' recurses and marks (0,1); (1,1)='F' fails; (0,0) is '#' and skipped; (0,2)='C' recurses and marks (0,2); its neighbours are (1,2)='C'≠'B', (0,3)='E'≠'B', and (0,1)='#'. All rejected, so (0,2) is restored to 'C' and False propagates. (0,1) has no untried neighbour, restores to 'B', returns False; (0,0) restores to 'A'. The outer loop then tries every other start cell and returns False.

Complexity and trade-offs

CostWhy
TimeO(R·C·3^(L-1))R·C start cells; 4 branches at the first expansion, 3 at every step after, since the cell you came from is marked
SpaceO(L)recursion depth ≤ L; no visited structure
vs. visited set+O(R·C) heap, one hash lookup per stepset[tuple[int, int]] or a bool matrix

Two cheap prunings before the search: if any letter of word occurs more times than it does in board, return False immediately (O(R·C + L)); and if word[-1] is rarer in the board than word[0], search for word[::-1] instead. The answer is identical and there are fewer start cells. Memoizing on (r, c, k) is not valid here: the set of cells already on the path is part of the state, so two visits to the same (r, c, k) can have different outcomes.

Failure modes

  • Sentinel collision. If the board can contain "#", the mark is indistinguishable from data and the search silently skips real cells. Pick a character outside the alphabet, or fall back to a visited set.
  • Board not restorable. A tuple of strings, a read-only NumPy array, or a board the caller still needs means in-place marking is off the table: use the visited set and pay the O(R·C).
  • Concurrent readers. Another thread reading the board mid-search sees "#" where a letter should be. The single restore point above removes the leak hazard (an early return True that skips the restore), but not the visibility hazard; that needs a copy or a lock.
  • Recursion depth. Python's default limit is 1000 frames. L ≤ 15 on the classic constraints is nowhere near it, but a word of length 10^4 on a large board raises RecursionError; convert to an explicit stack if L is unbounded.
  • Adversarial blowup. An all-'A' board with word = "A"*L explores the full 3^(L-1) tree. The character-count and reversal prunings are the cheap defenses; there is no polynomial algorithm for the general case.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-5

Describe constraint propagation and the evidence you would collect before relying on it.

Answer

Constraint propagation is the inference half of a CP solver: given the current domains, it repeatedly applies local rules that delete values no solution could use, until nothing more can be deleted. A fixpoint. It never guesses. Search branches on a variable; propagation runs again after every decision. So the two levers are how strong the propagation is and how much search is left.

Mechanism. Each constraint owns a propagator. For x + y = 10 with x ∈ [0,8], y ∈ [0,8], bounds propagation tightens x_min = max(0, 10 - y_max) = 2 and x_max = min(8, 10 - y_min) = 8, giving x ∈ [2,8] and symmetrically y ∈ [2,8]. Assign x = 3 and it collapses y to [7,7]. Arc consistency is stronger: for every value in a domain it checks a supporting value exists in each neighbour, deletes unsupported values, and re-queues affected constraints. AC-3 on a binary CSP is O(e·d³) worst case, e edges, d domain size.

LevelPrunesCost
Forward checkingneighbours of the just-assigned variablecheapest
Bounds consistencyinterval endpoints onlycheap, used for linear arithmetic on wide integer domains
Arc consistency (AC-3, AC-2001)every unsupported valueO(e·d³)
Singleton arc consistencytests AC after each tentative assignmentoften dominates search cost

CP-SAT (OR-Tools), Choco and Gecode mix these per constraint; you rarely choose one globally.

Trade-off. Stronger propagation removes more of the tree but costs more per node. The decision is empirical, not semantic: measure nodes explored and time per node. If propagation is more than roughly half of runtime, a weaker level usually wins.

Evidence before relying on it:

  1. Soundness. Enumerate all solutions on small instances with and without propagation; the counts must match. A propagator that deletes a value belonging to a solution is a bug, not a tuning choice.
  2. Fixpoint. Confirm the queue drains and no propagator re-fires forever.
  3. Undo. Every domain change must be trailed so backtracking restores state. Solve with restarts and compare against a no-restart run.
  4. Cost. Log propagation time versus search time and node counts across levels.
Python
candidates = {c: set(range(1, 10)) for c in cells}
trail = []

def assign(cell, digit):
    trail.append((cell, set(candidates[cell])))
    candidates[cell] = {digit}
    for peer in peers[cell]:
        if digit in candidates[peer]:
            candidates[peer].discard(digit)
            trail.append((peer, {digit}))

def rollback(mark):
    while len(trail) > mark:
        cell, removed = trail.pop()
        candidates[cell] |= removed

Trace: assign(A1, 5) with peers[A1] = {A2, A3} pushes (A1, {1..9}), then (A2, {5}), (A3, {5}). rollback(0) pops in reverse, restoring A3, A2, then A1 to {1..9}. Drop the trail and the state is corrupted on the first backtrack: a failure that hides on instances that never backtrack.

Failure modes: an unsound propagator returns a wrong answer silently; a missing trail entry corrupts state only on backtrack-heavy instances; a propagator that stops short of fixpoint is correct but slower.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-12

How does the N-queens formulation change if the workload grows by two orders of magnitude?

Answer

Pin down what grew first. If the board grew, n from 8 to 800, the formulation changes class, not just constant factors. If instead you mean 100× more boards at the same n, nothing about the formulation changes: you run the same solver more times and the only new question is scheduling. I'll answer the first reading, because that is the one that forces a redesign.

At n=8, backtracking enumerates all 92 solutions in microseconds. At n=800 exhaustive search is not a slower version of that: it is off the table. The solution count grows faster than exponentially (n=8: 92, n=12: 14,200, n=15: 2,279,184, n=16: 14,772,512), and the search tree is larger still. So you stop enumerating. Two reformulations survive: count solutions with a bitmask plus symmetry breaking, or construct a single solution directly. Explicit constructions exist for every n ≥ 4 and emit one in O(n) with no search at all.

The mechanism that makes counting viable is the bitmask. Three integers hold the attacked columns, the \ diagonal (row+col) and the / diagonal (row−col). A placement is one AND, one negate, one mask; the next candidate is avail & -avail.

Python
def count(n):
    full = (1 << n) - 1
    total = 0
    def place(cols, d1, d2):
        nonlocal total
        if cols == full:
            total += 1
            return
        avail = ~(cols | d1 | d2) & full
        while avail:
            bit = avail & -avail
            avail ^= bit
            place(cols | bit, (d1 | bit) << 1, (d2 | bit) >> 1)
    place(0, 0, 0)
    return total

Trace n=4: place(0,0,0) tries col 0, then col 2 (dead end), then col 3 → col 1 → col 2 reaches cols==full, total=1. Back at the top, col 1 → col 3 → col 0 → col 2 reaches full, total=2. count(4) returns 2, which is correct; count(8) returns 92. The shift directions are the whole trick: d1 moves left one column per row, d2 moves right one.

ApproachPer-node costWhat it buysBreaks when
Python setshash lookup per candidatereadable, fine to n≈15set overhead dominates
Bitmask ints3 word ops~10–50× fewer opsn > 64 without big ints
Symmetry breakingfix first queen to half the columnsup to 8× (dihedral group D4)you want total, not fundamental, count
Parallel split on first rownear-linearscales across coresuneven split → idle workers
ConstructiveO(n)one solution, no searchyou need the count, not one board

Failure modes. Bitmask overflow past n=64 silently corrupts the mask unless you use Python big ints or multiple words. Symmetry breaking double-counts if you forget it returns fundamental solutions, not the total. A parallel split on the first row is imbalanced because early columns prune differently.

When not to. If the task is "list all solutions for n=800," no formulation works: the count itself is astronomically large, so enumeration is impossible before it is slow. The honest answer is that the workload change forces you to say which question you are actually answering: one board, the count, or the list. Only the first two have a formulation at that scale.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-24

How does backtracking solve the Hamiltonian Cycle problem, and how do you prune paths that cannot visit all vertices?

Answer

Core answer (first 90 seconds). A Hamiltonian cycle is a closed walk through $G=(V,E)$ that visits every vertex exactly once. Deciding whether one exists is NP-complete (Karp, 1972), so exact search on arbitrary graphs means depth-first search with backtracking over the $(n-1)!$ cycles through a fixed start vertex. Fix $v_0 = 0$, any cycle rotates to start there, extend a path one vertex at a time, and prune any partial path that cannot be completed. The pruning is what makes it usable; without it you enumerate dead ends.

Mechanism. From the current endpoint $u$, try each unvisited neighbor $v$: mark, recurse, unmark on failure. Base case: path length $n$ and $u$ adjacent to $0$.

Python
def hamiltonian_cycle(graph: list[list[int]]) -> list[int] | None:
    n = len(graph)
    if n < 3:
        return None
    path, visited = [0], [False] * n
    visited[0] = True

    def available(w: int) -> int:
        # neighbors of w that are unvisited, or are one of the two open endpoints
        return sum(1 for x in graph[w]
                   if not visited[x] or x == 0 or x == path[-1])

    def search(u: int) -> bool:
        if len(path) == n:
            return 0 in graph[u]
        for v in graph[u]:
            if visited[v]:
                continue
            visited[v] = True
            path.append(v)
            if all(available(w) >= 2 for w in range(n) if not visited[w]) \
                    and search(v):
                return True
            path.pop()
            visited[v] = False
        return False

    return path + [0] if search(0) else None

Pruning. Three necessary conditions, checked after each extension:

  1. Degree. Every unvisited $w$ needs at least 2 available neighbors: unvisited vertices, or the two open endpoints $0$ and $u$. Fewer means $w$ cannot be entered and exited, so the branch is dead.
  2. Connectivity. The unvisited vertices plus the two endpoints must stay connected. If the current path cuts them into two non-empty components, no single cycle can thread both.
  3. Start closure. $0$ must keep at least one unvisited neighbor until the final step, or the cycle can never close.

Trace. Graph: 0:[1,2,5] 1:[0,2] 2:[0,1,3] 3:[2,4] 4:[3,5] 5:[0,4].

pathunvisitedcheckresult
[0,2,1]{3,4,5}vertex 3 has neighbors {2,4}; 2 is visited and not an endpoint (endpoints 1, 0) → available(3)=1prune
[0,2,3]{1,4,5}vertex 1 has neighbors {0,2}; 2 visited, not an endpoint (endpoints 3, 0) → available(1)=1prune
[0,1,2,3,4,5]{}length 6, 5 adjacent to 0cycle 0-1-2-3-4-5-0

The first branch 0-2 dies in two prunes; 0-1 succeeds.

Failure modes. Pruning strength tracks graph structure, not $n$. On dense graphs (say $G(n, 1/2)$) every vertex has degree $\approx n/2$, so available(w) >= 2 almost never fires and connectivity almost never breaks: the checks are near no-ops. Dense graphs are still easy in practice because a cycle exists with probability $\to 1$ and a Warnsdorff-style ordering (try the neighbor with fewest remaining options first) finds one in near-linear empirical time. The genuinely hard instances are sparse graphs near the Hamiltonicity threshold (average degree roughly 3–5) and graphs with a Hamiltonian path but no cycle, where the search must exhaust exponentially many dead ends to prove non-existence. Detect it by instrumenting node count, backtrack count, and prune count per rule: if prunes stay near zero while nodes grow super-linearly in $n$, you are on a pathological instance. Operationally the worst case is $(n-1)!$ nodes: $n=20$ is $\approx 1.2\times10^{17}$, infeasible, so run a node budget with a timeout and fall back. Memory is cheap: $O(n)$ stack and visited array.

Trade-offs. Held–Karp dynamic programming is exact in $O(n^2 2^n)$ time and $O(n 2^n)$ space: $n=20$ is $2^{20}\times20\approx21$M entries, about 168 MB at 8 bytes each. Feasible; $n=25$ is $\approx838$M entries, about 6.7 GB, not. So Held–Karp wins for small dense $n$ where backtracking's pruning is weak, while backtracking wins on sparse graphs where pruning is strong and memory is tight. Heuristics (nearest-neighbor, cheapest insertion, 2-opt/3-opt, Pósa rotation-extension) are fast with no guarantee. SAT and ILP encodings (successor variables plus no-subtour constraints, or subtour-elimination cuts) handle structured instances well. Backtracking is the wrong tool for large unstructured $n$, and for weighted TSP where you need proven optimality: use branch-and-bound with a Held–Karp lower bound instead.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-16

When does a backtracking search need to copy its path or board instead of mutating in place and undoing, and what does each choice cost in time and memory?

Answer

Copy the state only when it must outlive the call frame or cannot be inverted; otherwise mutate in place and undo. It is the same search: what changes is who owns the state and when it dies.

Mechanically, mutate-and-undo keeps one state alive plus the recursion stack: O(S + d) for state size S and depth d. Copy-per-node allocates S at every node, so a tree with N nodes costs Θ(N·S) copied elements over the run. Peak heap is O(d·S) if each copy dies with its branch, and O(frontier·S) the moment anything retains one: a worker thread, a results list, a cache.

mutate + undocopy per node
live memoryO(S + d)O(d·S) peak, O(frontier·S) if retained
total allocationO(N) scalar updatesΘ(N·S) elements copied
requiresan inverse op per mutationa cheap copy, no shared ownership
where it shows upsubsets, permutations, N-queens, word searchparallel search, memo keys, recording solutions

Subsets gives the arithmetic. Take n = 25, so 2^25 ≈ 33.5M nodes:

Python
# copy per node: every call builds a fresh tuple
def subsets(i, path):
    if i == n:
        out.append(path); return
    subsets(i + 1, path + (nums[i],))   # ~n elements per node -> ~8.4e8 element copies
    subsets(i + 1, path)

# mutate + undo: one list of at most n elements for the entire run
def subsets2(i):
    if i == n:
        out.append(path[:]); return     # one copy per *solution*, not per node
    path.append(nums[i]); subsets2(i + 1); path.pop()
    subsets2(i + 1)

Word search is the shared-board case. On a 20×20 grid searching for a length-10 word you explore roughly 3^10 ≈ 59,000 prefixes (each step has at most three neighbours it has not just come from). Marking a cell and unmarking it touches 400 + 10 cells over the whole run; copying the 400-cell board per node touches 400 × 59,000 ≈ 23.6M cells. Copying only the path is 10 × 59,000 ≈ 590k: survivable, which is exactly why the sloppy version passes review on small inputs.

The failure this invites is specific. In the aliasing direction, out.append(path) with no snapshot stores the same mutable list repeatedly and every result is identical. In the cost direction, the copy-per-node version passes the 5×5 test and dies when N·S outgrows the heap. Neither shows up before the input crosses the size the happy path used.

In practice, count nodes × state size before choosing. Single-threaded DFS gets one mutable state and a clean undo pair (append/pop, set/clear, +=/-=). Snapshot only where the result escapes: a leaf answer, a memo key, immutable tuples are what make functools.cache keys work, or a branch handed to another thread, where the undo is not the caller's to perform. Two Python notes: CPython's default recursion limit is 1000 and every frame costs memory, so a tree deeper than that needs an explicit stack or iterative deepening before copying is even the open question; and itertools hands you lazy iterators, so keeping results means materialising copies, which is why tee is documented as potentially needing significant auxiliary storage.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-23

How does testing a backtracking solution interact with rollback, and where do people ignore that?

Answer

Core answer

Backtracking keeps one mutable state object (the path, plus a used array or counts) mutates it on the way down, and undoes it on the way up. Rollback is that undo. Testing interacts with it in one specific way: a rollback bug almost never crashes or throws. It leaves stale state that the next branch reads, so it surfaces as a wrong result set: missing results, duplicated results, or both. The test that catches it is therefore a completeness test, not a validity test.

Assume a recursive solution with a single shared path and, where dedup is needed, a sorted input plus a used array or an index-based skip. Under those assumptions:

  • Assert the full result set equals a brute-force generator on small inputs. Checking each returned result is valid passes even when half the results are missing.
  • Assert state is restored: snapshot path (and used) before the loop, assert equality after it. This is the direct test of rollback and it fires at the exact frame that failed.

Why the undo step is where it breaks

Subsets-with-duplicates:

Python
def subsets_with_dup(nums):
    nums.sort()
    res, path = [], []
    def bt(start):
        res.append(path.copy())
        for i in range(start, len(nums)):
            if i > start and nums[i] == nums[i-1]:
                continue
            path.append(nums[i])
            bt(i + 1)
            path.pop()
    bt(0)
    return res

Trace nums = [1, 2, 2]:

  • bt(0): append []. i=0 → path [1], bt(1).
  • bt(1): append [1]. i=1 → path [1,2], bt(2).
  • bt(2): append [1,2]. i=2 → path [1,2,2], bt(3).
  • bt(3): append [1,2,2]; loop empty; return. pop → [1,2].
  • back in bt(2): i=2, 2>1 and nums[2]==nums[1] → skip. return. pop → [1].
  • back in bt(1): i=2, 2>1 and nums[2]==nums[1] → skip. return. pop → [].
  • bt(0): i=1 → path [2], bt(2) appends [2], then [2,2]; pop back. i=2 skipped.

Result: [[], [1], [1,2], [1,2,2], [2], [2,2]]. 6 subsets, correct.

Now delete the path.pop(). Nothing raises. bt(1) returns with path still [1], so the top-level i=1 branch appends onto [1] and you get [1,2], [1,2,2] where [2], [2,2] belong. The result set is wrong; the process is healthy. A validity-only test: "is each returned list a subset of the input?": passes, because every wrong result is still a valid subset.

Where dedup and rollback collide

The skip rule above reads start, which rollback never touches, so it is safe. The permutation variant is not:

Python
if used[i]: continue
if i > 0 and nums[i] == nums[i-1] and not used[i-1]: continue

Here the dedup predicate reads used[i-1]: state that rollback writes. If used[i] = False is restored at the wrong point (before the next iteration's skip check, or not at all), the prune decision changes, so one bug yields missing and duplicated permutations. This is the interaction people ignore: they test dedup and rollback as separate concerns, but the dedup predicate is a consumer of rollback's output.

Alternatives, and when differential testing is too expensive

  • Differential vs brute force: strongest, catches missing and extra. Cost is exponential in the brute force; fine to n≈8.
  • Mid-recursion invariants: assert path == snapshot after the loop, assert len(path) == sum(used). Cheap, runs at full scale, pinpoints the frame.
  • Property-based (Hypothesis) with lists(integers()) including duplicates: finds the minimal failing input, usually a two-element list with a repeat.
  • Known counts when brute force is worse than the solution: n-queens has 92 solutions at n=8 and 724 at n=10. Assert the count instead of enumerating.

Differential testing is too expensive when the brute force is a different exponential (n-queens) or when the solution is the brute force. Then invariants plus known counts are the fallback.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-6

In backtracking, how does the order in which you try candidate choices affect performance, and how do you choose a good order?

Answer

Ordering changes nothing about what backtracking returns and everything about how much of the tree you build before it gets there. Two independent levers.

Variable ordering sets the shape of the tree. The variable you branch on at a node sets the branching factor there, and that factor multiplies every node below it. The default is fail-first: branch on the thing most likely to fail, so the failure lands near the root where it is cheap. Concretely, MRV, minimum remaining values, picks the unassigned variable with the smallest current domain. Ties go to the degree heuristic: the variable in the most constraints with unassigned neighbours, because assigning it propagates further.

Value ordering sets the order of the leaves. Least-constraining value tries the value that eliminates the fewest options from neighbours, leaving the most room for the rest of the assignment. That is the right default when you want one solution. For optimisation, order values by the bound instead: try the value your bound likes first, so the incumbent improves early and branch-and-bound prunes harder.

The asymmetry matters and interviewers probe it: for all solutions, value ordering changes nothing about tree size, only the order solutions come out. Variable ordering changes the tree.

Why it compounds. If the root branches b ways and each subtree costs S nodes, the tree is roughly b·S. Take this 4×4 Sudoku partial state (digits 1–4, 2×2 boxes):

. . . . . . 1 . . 2 . . . . . .

Candidate counts after constraint propagation: R1C1 and R4C4 have four each; R2C2 and R3C3 have two each, both {3,4}; the remaining ten cells have three each. Row-major order branches on R1C1: four ways. MRV branches on R2C2 or R3C3: two ways, and the tie between them goes to degree. That is 2× at the root alone, and the same choice recurs at every level. On a 9×9 Sudoku where a fixed order stays 9-wide for 20 levels: 9^20 ≈ 1.2×10^19 nodes; 2-wide is 2^20 ≈ 1.05×10^6. That is why the heuristic reads as orders of magnitude on hard instances and as noise on easy ones.

python def select_unassigned(assignment, domains, neighbours): # MRV, tie-broken by degree return min((v for v in domains if v not in assignment), key=lambda v: (len(domains[v]), -sum(1 for n in neighbours[v] if n not in assignment)))

def order_values(var, domains, neighbours): # least-constraining value: fewest neighbour values eliminated return sorted(domains[var], key=lambda val: sum(1 for n in neighbours[var] if val in domains[n]))

Failure modes. MRV is bookkeeping: you maintain candidate counts and update them on assign and on undo. Where domains are uniform and propagation is cheap, that is overhead that buys nothing. MRV also minimises the current branching factor, not the subtree: it can pick a variable that fails fast and still leaves a wide tree underneath. It is a heuristic with no guarantee, and on adversarial instances a static order can beat it. Detect it by instrumenting nodes visited per depth: if the tree is still wide at depth 5 and beyond, the ordering is not biting.

When not to. If the instance finishes exhaustively in milliseconds, ordering is complexity you now have to test. If you are enumerating all solutions over uniform domains, variable ordering is the only lever that does anything.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-21

How does branch and bound prune a combinatorial search, and what makes a bound strong enough to actually cut work?

Answer

Branch and bound is backtracking on an optimisation problem with two extra pieces of state: an incumbent and a bound. The incumbent is the best complete solution found so far. The bound is an optimistic estimate of the best value any completion of the current partial solution can reach. When the bound cannot beat the incumbent, you discard the entire subtree, not because it contains no solutions, but because it contains no solution better than one you already hold.

For minimisation the test is if lower_bound(state) >= incumbent: return; for maximisation flip both. Note the >=: pruning ties is safe when you want one optimum and wrong when you need all of them.

The bound, concretely. Take TSP. Suppose there are 10 cities and, after committing to A → B → C, the partial tour costs 72. Every unvisited city must still be left exactly once, so a valid lower bound on the remaining cost is the sum of each unvisited city's cheapest outgoing edge:

cityDEFGHIJ
min outgoing edge3425342

bound = 72 + 23 = 95. If the incumbent is 88, prune: the subtree below this node holds 7! = 5040 leaf tours and you just deleted all of them for one linear scan. If the incumbent is 103, keep exploring.

Python
def dfs(visited, cost, last):
    global best, expanded, pruned
    lb = cost + sum(min_out[c] for c in unvisited(visited))   # optimistic
    if lb >= best:
        pruned += 1
        return
    if len(visited) == N:
        best = min(best, cost + dist[last][start])
        return
    expanded += 1
    for c in promising_first(visited):        # cheap children first
        visited.add(c); dfs(visited, cost + dist[last][c], c); visited.remove(c)

Why optimistic is a hard requirement. The min-outgoing sum is admissible because any completion genuinely pays at least that much: each unvisited city is departed from once, and its cheapest edge is a floor on that. Replace it with the average outgoing edge, or forget that one edge is already spoken for, and some completion gets estimated worse than it truly is. That branch is cut, the true optimum vanishes, and nothing throws: the search returns a valid tour, just not the best one. Same shape as an inadmissible heuristic in A*, which algs4's treatment of Dijkstra-with-a-lower-bound makes explicit: the estimate must never overstate how cheap the rest can be.

Tightness versus cost. A bound is only worth its arithmetic if it deletes more work than it costs:

boundcost per nodeillustrative node counts (25-city instance, hypothetical)
sum of min outgoing edgesO(n)~10⁵ nodes × ~1 µs
assignment-problem relaxation (Held–Karp)O(n³)~10³ nodes × ~200 µs
1-tree with degree penaltiesO(n²) after setup~10⁴ nodes, cheap updates

At 25 cities the cheap bound wins on wall clock; around 40 cities the expensive one usually does, because the leaf count is factorial and the bound cost is only polynomial. Pick by measuring node counts, not by taste.

Ordering is what makes bounds bite. Expand the most promising child first (for minimisation, the cheapest extension): the incumbent drops from +∞ to something real within the first few leaves, and every bound computed afterwards has something to compare against. Depth-first with a bad order and no seeded incumbent means the first thousand bounds prune nothing. A greedy tour seeded before the search costs O(n) and often doubles the pruning rate: hypothetical figure, but the direction is reliable.

Contrast with feasibility pruning. In N-Queens or Sudoku the prune test is a hard fact: a partial with a diagonal conflict extends to no solution. Branch and bound prunes partials that extend to perfectly valid solutions, just none better than the incumbent. So the soundness question changes from "is this conflict real?" to "can this estimate ever understate what is achievable?"

Failure modes and detection. An occasionally pessimistic bound silently returns a suboptimal answer and survives casual testing. Watch the >=/> tie choice when counting all optima, and compute bounds in integer arithmetic or round in the safe direction: a floating lower bound rounded up is inadmissible. Instrument expanded versus pruned, and validate the optimum against exhaustive search on n ≤ 8–9 instances before trusting it at scale.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-19

When would you run iterative-deepening DFS instead of plain DFS or BFS when the solution depth is unknown, and what does it cost?

Answer

Assumptions first: every move costs the same, so depth in moves equals cost, and the solution depth is unknown but expected to be modest. Under those, iterative deepening DFS is what I reach for when the BFS frontier will not fit and I still want the shallowest solution.

Mechanically it is a loop: depth-limited DFS with bound 0, then 1, then 2, ... until a pass returns a goal. Each pass is a plain DFS holding one path of d frames. Because the bound grows by one each time, the first goal found is at minimum depth: BFS's guarantee, bought with DFS's memory.

What it costs is re-expansion of the upper levels on every pass. Take branching factor 3, solution at depth 12:

Plain DFSBFSIDDFS
Peak memoryd = 12 framesup to 3^12 = 531,441 queued states12 frames
First goal returnedany, order-dependentshallowestshallowest
Nodes expandedorder-dependent797,1611,195,735

BFS expands 1 + 3 + ... + 3^12 = (3^13 - 1)/2 = 797,161 nodes and queues up to 531,441 states at the deepest level: roughly 50 MB at 100 bytes per state before you count the visited set. IDDFS expands sum over passes = 1,195,735 nodes, 1.5x BFS, while holding 12 frames. That 1.5x is the general shape: the last pass dominates, so total work is b/(b-1) times one full search. Branching factor 2 gives 2x, factor 10 gives 1.11x, factor 3 gives 1.5x.

The b >= 2 condition is doing real work in that formula. On a chain of d moves (b = 1) there is no geometric growth to dominate: each pass costs L nodes and the total is (d+1)(d+2)/2 = O(d^2) against d for a plain DFS. "Constant-factor overhead" is a claim about branching factors, not a law.

When I would not use it:

  • Shallow but wide, no depth-based cutoff. If depth is already small, a plain DFS holds the same 12 frames and the repeated passes are pure waste. Same when I must enumerate every solution or prove none exists: IDDFS redoes the whole tree once per bound and gets nothing for it.
  • Weighted moves. Depth is not cost. With moves costing 1, 3 or 10, IDDFS returns fewest moves, not cheapest, and I want Dijkstra or A*.
  • Cycles in a graph. A global visited set is the Theta(|V|) memory I was trying to avoid; a per-pass visited set re-expands everything shared. Keeping only ancestor checks preserves O(d) memory and re-expands subtrees.
  • Expensive state. If generating a node means copying a board at 200 us, the 1.5x multiplier hits wall clock, not just counters.

Where memory is acceptable, plain BFS with a visited set expands each state once and is easier to reason about; if both endpoints are known, bidirectional BFS at b=3, d=12 drops the frontier from 531,441 to 2 * 3^6 = 1,458.

Two failure modes worth naming. The classic one is checking for a goal only when generating children: a goal sitting exactly at the bound is never accepted, every pass misses it, and the loop never terminates. Test the goal on visit, before the depth cutoff. The other is state that does not fully undo between passes, so pass 2 sees a board pass 1 left dirty. Both show up in counters: expansions per pass should track b/(b-1) times one full pass. Orders of magnitude more means a cycle or a broken undo.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-17

When does recursion depth become a failure mode in a backtracking search, and how would you detect it and fix it with depth limits, bounding the search, or an explicit stack?

Answer

Depth becomes a failure mode as soon as it scales with the input instead of being a constant, and it bites on the first descent: long before the exponential runtime does. One root-to-leaf path to depth n costs n frames and n steps. You never have to explore the huge tree to crash; a single unpruned walk kills you.

So the first thing I do before writing the recursion is write the depth as a function of the input:

ProblemMax depth on one pathDepth a failure mode?
Word search, word length kkNo: bounded by the word, usually 5–10
Sudoku81No: constant
Permutations / subsets of n itemsnYes
DFS over a graph|V|Yes: a path-shaped graph of 10^6 nodes is depth 10^6 for linear work
Search over nested or unbounded structureinput-definedYes, and nobody sized it

If that column says it grows, the recursion is a design decision, not an implementation detail.

What failure looks like differs by runtime. CPython (checked against 3.14): sys.getrecursionlimit() is 1000 by default, Python calls count against it, and you get a RecursionError. sys.setrecursionlimit() raises the frame count but not the C stack under it, and the docs explicitly warn that too high a value crashes the interpreter: a segfault, not an exception. On the JVM (HotSpot) nothing is counted per call; the thread stack (-Xss, commonly 1 MB, platform default: read yours) runs out and throws StackOverflowError, an Error raised at an unpredictable call site. In C++ nothing is checked at all: you run off the end of the stack (8 MB for the main thread on typical Linux, see ulimit -s) and take SIGSEGV with no cleanup. Frames are also not equal: a C++ frame is tens of bytes of spilled locals, a Python frame is a whole frame object with a locals mapping, so the same depth is not the same memory.

Fixes, in the order I take them:

  1. Bound the search. If no valid solution goes deeper than D, say so as an invariant and assert it. If depth grows with input, look for pruning, constraint propagation, or a better formulation that cuts whole subtrees: that buys depth and time together.
  2. A depth limit with a stated decision at the boundary: return "no solution shallower than D" or fail the request. It is only correct when you can prove nothing valid lives below the cutoff; otherwise it quietly turns solvable inputs into false negatives.
  3. An explicit stack. Rewrite choose-explore-unchoose as a loop over a heap stack (Python list, ArrayDeque, std::vector). The runtime limit disappears and you own the frame encoding, choice index plus mutated state, and the undo. Costs more code and reads worse. Tail-call elimination does not apply: backtracking has two recursive calls and work (the undo) after each one.

The traps: catching RecursionError and continuing the search, since it fires at an arbitrary call site and anything the frame already did is only unwound if undo lives in finally; raising the limit in a service worker until it segfaults and takes other requests with it; and shipping a depth cap that isn't in the spec, which reports "no solution" instead of crashing and is therefore harder to detect than the crash it replaced.

Detect it cheaply: assert the depth, log a high-water mark, and run CI with a shrunken stack (threading.stack_size(), ulimit -s, -Xss) so the failure reproduces on a laptop at small input.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-20

What trade-off does symmetry breaking force that a junior answer usually skips?

Answer

The trade-off is that symmetry breaking shrinks the search by giving up the solver's ability to answer questions about solutions. Post the symmetry-breaking constraint and the search enumerates orbit representatives, not solutions. Existence, and the optimum of a symmetry-invariant objective, survive. Counting, enumeration, and any query about one specific solution do not, because those questions are not invariant under the group. "It divides the search by |G|" is where the junior answer stops; the bill arrives when the result has to be read back in problem space.

The inverse of the reduction is not a division. An orbit is only |G| in size when the solution inside it has no symmetry of its own, so the true count comes back as a sum over orbits.

8-queens, with real numbers. 92 solutions. The board's symmetry group is the dihedral group of order 8: four rotations times two reflections. The 92 solutions fall into 12 orbits - eleven of size 8 and one of size 4, the orbit of the placement that a 180-degree rotation leaves unchanged (rows 4 6 8 2 7 1 3 5 by column).

92 = 118 + 14 = 88 + 4

92/8 = 11.5, not an integer, and a symmetry-broken enumeration hands back 12 boards. 128 = 96 overcounts by exactly those 4 short-orbit solutions. Recovering 92 needs each orbit's stabilizer, which is the information the broken search stopped producing. Burnside's lemma is the general form: orbits = (1/|G|) * sum over g in G of |Fix(g)|. Here (92 + 4 + 60)/8 = 12: the identity fixes all 92, the 180-degree rotation fixes 4, and the remaining six elements fix none.

Python
from itertools import permutations

N = 8
sols = [p for p in permutations(range(N))
        if all(abs(p[c] - p[d]) != d - c
               for c in range(N) for d in range(c + 1, N))]   # p[col] = row

def rot(p):                      # (c, r) -> (r, N-1-c)
    q = [0] * N
    for c in range(N):
        q[p[c]] = N - 1 - c
    return tuple(q)

def flip(p):                     # (c, r) -> (N-1-c, r)
    return tuple(reversed(p))

def apply(p, k, f):
    for _ in range(k):
        p = rot(p)
    return flip(p) if f else p

group = [lambda p, k=k, f=f: apply(p, k, f)
         for k in range(4) for f in (False, True)]

seen, sizes = set(), []
for s in sols:
    if s in seen:
        continue
    orb = {g(s) for g in group}
    seen |= orb
    sizes.append(len(orb))

print(len(sols), len(group), sorted(sizes))
# 92 8 [4, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8]

The sols list is 92 tuples, the group is the 8 distinct transforms, and the orbit sizes come back as one 4 and eleven 8s, so the honest count is 11*8 + 4.

QueryPreserved after symmetry breaking
does a solution existyes
optimum of a symmetry-invariant objectiveyes
how many solutionsno - the search now returns 12, not 92
all solutions up to isomorphismyes, that is the point
is there a solution with a queen in column 0no - you get the answer for canonical forms, a different question
"give me another solution"no - canonical form returns the same representative every time

The expensive failure is breaking a symmetry of the encoding that is not a symmetry of the problem. Five identical machines in a job shop are interchangeable; add a sixth with a longer setup time, keep the machine-symmetry constraint, and the optimum that puts work on the slow machine is pruned. The solver still returns a feasible schedule with a worse objective, so it does not fail loudly - the check is to solve small instances twice, symmetry breaking on and off, and compare optima, not feasibility. Nor is it free per node: a lex-leader encoding over a wide variable array adds clauses and propagators at every node, so if the pruned subtrees were ones a good heuristic never entered, the node count falls while wall-clock time rises. Track nodes and time separately. And because representatives are canonical, any downstream stage that samples "a valid solution" for diversity sees the same board repeatedly.

Break symmetry when you can prove the group acts exactly on the feasible set and the query is existence, an invariant optimum, or enumeration up to isomorphism. Keep the unbroken search, or reconstruct from representatives and their stabilizers, when the query names a specific solution or when the symmetry is only approximate.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-11

What would you measure before treating reuse of elements as settled?

Answer

Assume the combination-sum family: a candidate list, a target, and a recursive combine(remaining, start) that either passes the same index (reuse) or the next one (no reuse). Before I'd call reuse settled I'd measure three things, in order: that the recursion terminates, that the output matches a reference, and what the search tree costs at the real scale. The first two are gates; the third decides whether reuse is affordable.

Termination: the strictly decreasing quantity. Reuse passes start=j, so the only thing that shrinks is remaining. That holds iff every candidate is positive. Measure min(candidates): if it's ≥ 1, depth is bounded by target / min(candidates); if any candidate is 0 or negative, remaining can stay flat and the recursion never bottoms out. So the first measurement is a one-line assertion, not a profiler run.

Python
def combine(candidates, remaining, start, out, path):
    if remaining == 0:
        out.append(path[:]); return
    if remaining < 0:
        return
    for j in range(start, len(candidates)):
        v = candidates[j]
        path.append(v)
        combine(candidates, remaining - v, j, out, path)      # reuse
        # combine(candidates, remaining - v, j + 1, out, path)  # each once
        path.pop()

Correctness: compare against a reference. Run both variants on a corpus of small inputs and diff the solution sets. On candidates=[2,3,6,7], target=7:

variantcallrecursive callssolutions
reusecombine(t-v, j)28[2,2,3], [7]
no reusecombine(t-v, j+1)13[7]

The counts are the number of combine invocations, counted by hand on that input. Reuse finds one extra solution and does ~2.2× the calls. If your reference and your reuse run disagree on any input, reuse is wrong, not slow.

Cost: node count and wall-clock at scale. The branching factor at a node is len(candidates) - start, the same for both variants; reuse just keeps it high for longer, so depth goes from len(candidates) to target / min(candidates). Measure recursive-call count (instrument a counter) and wall-clock at the target you actually ship. With min(candidates)=1 and target=1000, depth is 1000: check the stack limit before you check the clock.

When not to measure. If the input is small or the run is one-off, the termination assertion plus a reference diff is enough; profiling a 13-call tree is noise. And if the problem says each element once, reuse isn't a tuning knob: it's the wrong model, and no measurement rescues it.

Failure modes to detect. Non-termination from a zero/negative candidate: catch with a depth cap. Duplicate solutions when candidates repeat and you don't dedupe: catch by comparing solution count to the reference. Exponential blowup: catch by counting calls at the real target, not at target=7.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-14

When would you refuse a design because of memoisation versus backtracking?

Answer

Refuse memoisation when the cache key can't be made compact without changing the answer, when you need every solution rather than one value, or when the table's memory exceeds the budget. Otherwise memoise.

Memoisation collapses the backtracking tree into a DAG over distinct states. The speedup is exactly the ratio of tree nodes to distinct states. When that ratio is near 1, you've added a hash table and bought nothing. That ratio is the whole decision.

The state is the path.

Python
from functools import cache

@cache
def dfs(node, path):                 # path: tuple of visited nodes
    if node == target:
        return 1
    return sum(dfs(n, path + (n,)) for n in adj[node] if n not in path)

Every call carries a distinct path, so the cache never hits. You pay tuple construction and hashing O(depth) per call and store one entry per node visited: O(V) memory for zero reuse. Refuse; prune instead.

You need all solutions. Counting Hamiltonian paths memoises on (current, visited_bitmask): n·2^n states. At n=12 that's 12·4096 = 49,152 entries and roughly n²·2^n ≈ 590k edge relaxations. Enumerating them caches lists of paths instead, and the total stored is the number of paths: 12! ≈ 4.8×10^8 for K12. The cache has become the output. Refuse and stream solutions.

Memory. The same bitmask DP at n=30 is 30·2^30 ≈ 3.2×10^10 entries; at 8 bytes each, ~258 GB. At n=25 it is 25·2^25 ≈ 8.4×10^8 entries, ~6.7 GB: already past a laptop. Refuse, or switch to branch-and-bound with a tight lower bound.

Pruning already wins. In branch-and-bound the bound cuts subtrees before they are expanded. A memo table only helps states you actually reach, and a cached value computed under one bound is not valid under a different one, so the two techniques do not compose cleanly. If the bound prunes to a few million nodes, the table is pure overhead.

Correctness, not cost. If the answer depends on more than the key (cost-so-far in a shortest-path search, a constraint the key omits) memoising on the partial key returns a wrong value silently, and it passes casual testing because the happy path often hides it. If the state graph has cycles, plain @cache recurses forever; you need an in-progress sentinel.

SituationMemoise?Why
Grid paths, state (r, c)YesR·C states vs C(R+C−2, R−1) paths
Visited-set state, countingYesn·2^n states
Visited-set state, enumeratingNocache holds every path
State includes the path tupleNozero hit rate
Bound prunes hardNotable can't be shared across bounds

Deciding. Ask three questions in order: does the key capture everything the answer depends on? does the key repeat across the search? does the table fit? Yes/yes/yes → memoise. Any no → prune, stream, or bound.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-18

How do you decide a problem calls for backtracking rather than greedy, dynamic programming, or plain enumeration?

Answer

It comes down to two questions, asked in this order: what has to come out (one feasible solution, all of them, or an optimum) and what structure the objective has. Backtracking is the answer when you need feasible solutions under constraints that can be checked on a partial assignment, and there is neither a safe local choice nor overlapping subproblems to reuse.

signaturetoolwhy
every output is valid, nothing to pruneplain enumerationsubsets of n elements are 2^n outputs and all of them are legal
a local choice provably extends to an optimumgreedyan exchange argument exists: earliest-finish activity selection
optimal substructure + overlapping subproblemsDPmin coins: f(A) = 1 + min over c of f(A-c)
feasibility checked on a partial choice, no safe local movebacktrackingN-queens, Sudoku, word search

Greedy versus backtracking is decided by whether a local move is safe. Activity selection: take the earliest-finishing job that starts after the last one taken; an exchange argument shows any optimum can be rewritten to start with it, so one pass over the sorted list is enough. N-queens has no such move. Placing a queen in the emptiest-looking column can make the rest infeasible, and no local scoring tells you which column is right. Eight queens is 8! = 40,320 raw placements and 92 solutions; what saves the search is abandoning a partial board the moment two queens share a diagonal.

DP versus backtracking is decided by whether states repeat. Minimum coin change, coins {1,3,4}, amount 6: greedy largest-first takes 4+1+1 = 3 coins where the optimum is 3+3 = 2. A backtracking search over coin choices also finds 2, but it re-explores every path that reaches the same remaining amount. At amount 6 that is a few hundred paths against a 3 x 6 = 18-entry table, who cares. At amount 600 the search tree is astronomical while the table is 3 x 600 = 1,800 entries. The diagnostic is a count: nodes visited far above distinct states reached. Add a memo to that search and you have top-down DP, which is the honest admission that the problem was never a search problem.

Enumeration versus backtracking: subsets of 25 elements is 33.5M outputs and every one is valid, so there is nothing to prune and itertools.combinations is the right tool. Ask instead for subsets with no two adjacent elements, and the same tree gains a feasibility check at every node: that is backtracking.

The interview lists organise this by pattern family: unconstrained generation (subsets, permutations, combinations), constrained board search (N-queens, Sudoku, word search), and optimisation over combinations. The family tells you which recursion to reach for. The two questions above tell you whether to reach for it at all.

Failure modes: backtracking for min-coins is correct and exponential. Catch it with the state-versus-node count before the input grows. Greedy for coin change is fast and wrong: catch it with a counterexample at small amounts, not with a benchmark. And a bound that is not admissible prunes the optimum clean out of the search while every test still passes.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-22

When a backtracking search has an exponential worst case, when is shipping it the right call and when do you refuse? Walk me through the reasoning.

Answer

Shipping an exponential-time search is the right call when the bound is a fact about the tree, the instances in front of you never get near it, and you can show that with a measurement rather than a feeling. The assumptions I would state up front: n is capped by the API or by the business, the search runs inside one request under a node or time budget, and the number of solutions that must be materialised is small.

The raw sizes are why the bound cannot be waved away. Subsets give 2^n leaves: 2^20 = 1,048,576, 2^25 = 33,554,432, 2^30 = 1,073,741,824. Permutations are worse: 10! = 3,628,800, 12! = 479,001,600, 15! = 1,307,674,368,000. At 10^8 iterations per second that last one is about 3.6 hours of pure traversal before any work per node. So "exponential but fine" is true while n is small and false the moment it isn't: the bound is what tells you the ceiling on n.

What buys room past that ceiling is pruning collapsing the effective branching factor. A pruned search behaves like b_eff^n, where b_eff is measured, not assumed:

depth nb = 2, no pruneb_eff = 1.3
201,048,576~190
2533,554,432~706
301,073,741,824~2,620

Same n, five or six orders of magnitude apart. That gap is exactly why solvers decide instances whose worst case is intractable, and it is why the two statements "SAT is NP-complete" and "this solver handles a million variables" are both true.

The evidence I want is node counts, not wall-clock time. Instrument the recursion:

Python
# Python 3.12 -- count nodes with and without the early prune.
# Positive integers; counts subsets of `nums` summing exactly to `budget`.
def count_nodes(nums, budget, use_prune):
    nums = sorted(nums)
    suffix = [0] * (len(nums) + 1)
    for i in range(len(nums) - 1, -1, -1):
        suffix[i] = suffix[i + 1] + nums[i]
    nodes = 0

    def dfs(i, left):
        nonlocal nodes
        nodes += 1
        if left == 0:
            return 1
        if i == len(nums):
            return 0
        if use_prune and suffix[i] < left:   # nothing left can reach the target
            return 0
        if nums[i] > left:                   # sorted: every later value is larger
            return 0
        return dfs(i + 1, left - nums[i]) + dfs(i + 1, left)

    return dfs(0, budget), nodes

With the prune off, that walk covers essentially the whole tree: 2^25 leaves, about 67 million nodes. With it on, the count is whatever the instance allows, and that number, reported next to p50 and p99 across a batch of production-shaped inputs, is the evidence. Wall-clock time hides the shape of the tree behind I/O and garbage collection.

The hard instances are predictable. Weak or absent constraints mean the prune never fires. Violations that only become visible at the last assignment, a permutation that fails a global check only at depth n, make every leaf cost a full path. Duplicate-heavy or adversarially ordered input can also defeat a heuristic that worked on your test set. The tell is a node-count histogram with a fat tail: p50 of 2,000 nodes and p99 of 40 million on the same code is a prune that fires on average and dies on the instances that matter.

Against that: check the constraint the moment the assignment is made rather than at the leaf, order the choices most-constrained-first so dead branches surface early, and add a bound on cost-so-far where an objective exists (branch and bound). Each of these moves violations earlier in the tree, which is where the leverage is.

The decision rule I would actually apply: accept backtracking if the raw worst case at the maximum allowed n already fits the budget, say 2^25 with a cheap node is milliseconds, or if the pruned node count is measured orders of magnitude below the tree and the search carries a hard node cap with a defined fallback. Otherwise pick something whose cost does not depend on the input's structure: greedy (fast, no guarantee), dynamic programming (subset sum is O(n·W) pseudo-polynomial, a win only when W is small), an approximation (knapsack has an FPTAS), or a bounded-depth / iterative-deepening search. Calling it "fast in practice" without either a bound on n or a measured prune is how a p99 timeout reaches production.

Curated: · Written: · Reviewed:

Difficulty: Hard