Choose, Explore, and Undo

Some interview problems ask for every possibility: every combination of settings, every order of a playlist, every way to reach a total. Others ask whether any possibility works at all, such as whether a word can be traced on a board. You can’t compute those answers with a formula, so you build candidates one choice at a time. When a choice leads nowhere, you step back and try the next one. That stepping back is what gives backtracking its name.

Choose, Explore, Undo

Every backtracking function repeats a three-beat rhythm. Commit to one option, hand the rest of the problem to a recursive call, and take the option back when that call returns, so its sibling starts from the same state you had. Here’s the smallest version, which lists every on/off combination of three feature flags:

Language: JavaScript
const flags = ["beta", "dark", "offline"];
const chosen = [];
const settings = [];

function decide(i) {
  if (i === flags.length) {
    settings.push([...chosen]);
    return;
  }
  chosen.push(flags[i]);
  decide(i + 1);
  chosen.pop();
  decide(i + 1);
}

decide(0);
console.log(settings);

Each flag is either switched on or left off, so three flags give 2³ = 8 settings:

Language: Program Output
[
  [ 'beta', 'dark', 'offline' ],
  [ 'beta', 'dark' ],
  [ 'beta', 'offline' ],
  [ 'beta' ],
  [ 'dark', 'offline' ],
  [ 'dark' ],
  [ 'offline' ],
  []
]

The push() before the first recursive call is the choice, and the pop() after it is the undo. One shared chosen array serves the whole search, which keeps memory at O(n) for the path itself. When an interviewer asks about cost, start from the number of results: 2ⁿ subsets, n! orderings, and so on, each taking up to O(n) to copy.

Prune Branches That Can’t Work

Listing everything is often unavoidable. Exploring branches that can’t produce a result is not. If you can tell early that a partial answer is doomed, stop and return. Sorting first often makes that check cheap:

Language: JavaScript
const prices = [5, 9, 3, 7].toSorted((a, b) => a - b);
const basket = [];
let calls = 0;

function fill(start, left) {
  calls++;
  if (left === 0) {
    console.log(basket.join(" + "));
    return;
  }
  for (let i = start; i < prices.length && prices[i] <= left; i++) {
    basket.push(prices[i]);
    fill(i + 1, left - prices[i]);
    basket.pop();
  }
}

fill(0, 12);
console.log(`${calls} calls`);

The search finds both baskets that cost exactly 12 and makes only nine calls along the way:

Language: Program Output
3 + 9
5 + 7
9 calls

Two details do the pruning. Starting each loop at start means a basket is only ever built in increasing order, so 5 + 7 and 7 + 5 can’t both appear. And because the prices are sorted, the loop stops as soon as a price is bigger than what’s left, since every later price is bigger too.

JavaScript Details That Interviewers Notice

Pushing the path stores a reference, not a snapshot. Arrays are objects, so saving one saves a pointer to it, and later changes show through:

Language: JavaScript
> const path = ["css"];
undefined
> const saved = [path, [...path]];
undefined
> path.pop();
'css'
> saved
[ [], [ 'css' ] ]

The first entry emptied along with path, while the spread copy kept its contents. Write results.push([...path]) at the moment a result is complete.

Every push() needs exactly one pop(). An early return or continue placed between them leaves a stale item behind, and every later result inherits it. Keep the choose and undo lines next to the recursive call, with nothing that can skip the undo.

Track used cells in a Set of numbers or strings. Strings can’t be changed in place, so you can’t mark a letter on a board of strings as visited, and a module, which always runs in strict mode, throws a TypeError if you try. A Set of [row, col] arrays doesn’t work either, because set.has([1, 2]) compares by reference and is always false. Store row * cols + col or `${row},${col}` instead.

Sort a copy. sort() reorders the caller’s array. toSorted((a, b) => a - b) returns a sorted copy, and the comparator matters: without it, [10, 5] sorts as strings and stays [10, 5].

In this section, you’ll review an AI-written topping combiner that stores the wrong thing, list every order of a playlist under an artist rule, plan coupon combinations, and trace words on a game board.

Become a Member to join the conversation.