CodingPatterns9 min read

Backtracking: Searching Every Option Without Getting Lost

This lesson is for candidates in software and data coding rounds who freeze when a problem says "return all" or "find every way". Backtracking is the pattern behind those problems. By the end you will have one template that covers subsets, permutations, combinations and constraint puzzles, you will know how to state its complexity, and you will know how pruning makes it fast enough.

How to spot a backtracking problem

Three cues point to backtracking:

  • The output is a list of all valid answers, not a single number: all subsets, all arrangements, all ways to split a string.

  • The answer is built one decision at a time, and each decision limits the next: pick an element or skip it, place an item in a slot, cut the string here or later.

  • The input is small. Exhaustive search grows exponentially, so problems that need it keep n small. With n up to about 20, think 2^n (about one million). With n up to about 10, think n! (10! is 3,628,800).

If the problem asks only for a count or the best value, check dynamic programming first: counting rarely needs every answer listed. If it asks to list them, backtracking is usually the honest answer.

How backtracking problems are judged

The SmartIntervu coding report scores problem solving, correctness, code quality, testing and edge cases, and communication. Backtracking is won in problem solving and communication: saying what one choice is, when an answer is complete, and how big the search can get, before you type. It is lost in correctness, almost always on one of two lines: recording the shared array instead of a copy, or undoing only part of a choice. For testing, name an empty input, an input with duplicates, and a target nothing can reach.

The contrast is easy to hear. A weak candidate on combination sum writes a loop that recurses, gets [2, 2, 3], [2, 3, 2] and [3, 2, 2], and tries to remove duplicates afterward with a set of sorted tuples. A strong one says first: "Each step picks the next number, never smaller than the last, so every combination comes out in one order only. I stop when the remaining sum is 0, and cut the branch when the next number exceeds it." The second candidate has no duplicates to remove, and the interviewer has already heard the pruning rule. When a candidate is stuck, the interviewer's hint is usually "draw the first two levels of the tree", so draw it.

The template: choose, explore, unchoose

Picture the search as a tree. The root is the empty answer. Each edge is one decision. Each leaf is a complete candidate. Backtracking walks that tree depth first, keeping one partial answer and undoing each decision after exploring it.

function backtrack(state: PartialAnswer): void {
  if (isComplete(state)) {
    record(copyOf(state));
    return;
  }
  for (const choice of choicesFrom(state)) {
    if (!isValid(state, choice)) continue; // prune
    apply(state, choice);    // choose
    backtrack(state);        // explore
    undo(state, choice);     // unchoose
  }
}

Three things in this sketch decide whether your solution is right:

  1. What a choice is. Say it out loud before coding: "at each step I decide which element comes next" or "at each index I decide include or skip".

  2. When the answer is complete. A fixed length, a target reached, or the input consumed.

  3. Copy on record. The partial answer is one shared array that keeps changing. Push a copy into the results, or every result ends up as the same empty array.

Subsets: every node is an answer

For subsets, each node of the tree is already a valid answer, so you record on entry rather than at the leaves. Passing a start index means each element is considered only after the ones before it, which avoids producing [1, 2] and [2, 1] as different subsets.

function subsets(nums: number[]): number[][] {
  const result: number[][] = [];
  const current: number[] = [];

  function explore(start: number): void {
    result.push([...current]); // every node is a subset
    for (let i = start; i < nums.length; i++) {
      current.push(nums[i]); // choose
      explore(i + 1);        // explore
      current.pop();         // unchoose
    }
  }

  explore(0);
  return result;
}

There are 2^n subsets and copying one costs up to n, so the time is O(n * 2^n). The recursion depth is n, so extra space beyond the output is O(n).

When the input has duplicates

With [1, 2, 2] the code above returns [1, 2] twice. Sort the input, then skip a value that equals the one before it at the same level of the tree:

nums.sort((a, b) => a - b);
// inside the loop, before choosing:
if (i > start && nums[i] === nums[i - 1]) continue;

The condition i > start matters. It skips the duplicate as a sibling (the same choice at the same level), but still allows it deeper in the tree, so [1, 2, 2] and [2, 2] both appear. Trace it once by hand and you get exactly six subsets: [], [1], [1, 2], [1, 2, 2], [2], [2, 2].

Permutations: track what is used

In a permutation every element appears once, in any order, so the choices at each step are "any element not used yet". A boolean array tracks that.

function permutations(nums: number[]): number[][] {
  const result: number[][] = [];
  const current: number[] = [];
  const used: boolean[] = new Array(nums.length).fill(false);

  function explore(): void {
    if (current.length === nums.length) {
      result.push([...current]);
      return;
    }
    for (let i = 0; i < nums.length; i++) {
      if (used[i]) continue;
      used[i] = true;
      current.push(nums[i]);
      explore();
      current.pop();
      used[i] = false;
    }
  }

  explore();
  return result;
}

There are n! leaves and each copy costs n, so the time is O(n * n!). Notice that undo must reverse every part of choose: both the push and the used flag. Forgetting one of them is the most common bug in this pattern.

Combinations with pruning

Pruning is cutting a branch as soon as you can prove it holds no answer. It is what turns an exhaustive search into one that finishes in time.

Take this problem: given distinct positive integers and a target, list every combination that sums to the target, where each number may be used more than once. With [2, 3, 6, 7] and target 7 the answer is [2, 2, 3] and [7].

function combinationSum(candidates: number[], target: number): number[][] {
  const sorted = [...candidates].sort((a, b) => a - b);
  const result: number[][] = [];
  const current: number[] = [];

  function explore(start: number, remaining: number): void {
    if (remaining === 0) {
      result.push([...current]);
      return;
    }
    for (let i = start; i < sorted.length; i++) {
      // Sorted input: if this candidate is too big, so is every later one.
      if (sorted[i] > remaining) break;
      current.push(sorted[i]);
      explore(i, remaining - sorted[i]); // i, not i + 1: reuse is allowed
      current.pop();
    }
  }

  explore(0, target);
  return result;
}

Two details carry the solution. Passing i rather than i + 1 allows reuse while still keeping each combination in non-decreasing order, so [2, 2, 3] is never also produced as [3, 2, 2]. And sorting turns the bound check into a break instead of a continue, which cuts the whole rest of the level at once.

Trace it: from 7 you take 2, 2, 2 and reach 1, where every candidate is too big. Back up to 3 remaining, take 3, and record [2, 2, 3]. The 6 and 7 branches below that fail the bound immediately. Back at the root, 3 leads to dead ends at 4 and 1 remaining, 6 leaves 1, and 7 reaches 0 and records [7].

Constraint problems: validate as you go

Many backtracking problems are puzzles with rules: place items so none conflict, or split input so every piece is valid. The skill is checking each rule at the moment a choice is made, not after the answer is complete.

Example: given a string of digits, list every valid IPv4 address you can form by inserting three dots. Each of the four parts must be 0 to 255 with no leading zero (so "0" is fine but "01" is not).

function restoreIpAddresses(s: string): string[] {
  const result: string[] = [];
  const parts: string[] = [];

  function explore(start: number): void {
    const partsLeft = 4 - parts.length;
    const charsLeft = s.length - start;
    if (partsLeft === 0) {
      if (charsLeft === 0) result.push(parts.join("."));
      return;
    }
    // Each remaining part needs 1 to 3 digits.
    if (charsLeft < partsLeft || charsLeft > partsLeft * 3) return;

    for (let len = 1; len <= 3 && start + len <= s.length; len++) {
      const part = s.slice(start, start + len);
      if (part.length > 1 && part[0] === "0") break; // longer parts keep the zero
      if (Number(part) > 255) break;                 // longer parts only grow
      parts.push(part);
      explore(start + len);
      parts.pop();
    }
  }

  explore(0);
  return result;
}

For "25525511135" this returns 255.255.11.135 and 255.255.111.35. The length check prunes hard: taking just 2 as the first part leaves 10 digits for 3 parts, which can hold at most 9, so that branch dies at once instead of trying every split. The tree has at most 3^4 = 81 leaves, so the search is effectively constant time, a fact worth saying out loud.

Stating the complexity

Interviewers expect you to bound an exponential algorithm honestly rather than call it "fast". Use this formula: the number of nodes the search visits, times the work per node.

  • Subsets: 2^n nodes, O(n) to copy, so O(n * 2^n).

  • Permutations: about n! leaves (and fewer than e * n! nodes in total), O(n) per copy, so O(n * n!).

  • Combinations of size k from n: C(n, k) answers, O(k) each.

Pruning rarely changes the worst case, and you should say so: "In the worst case this is still exponential, but the bound check cuts every branch whose sum passes the target, so in practice we visit far fewer nodes." That sentence shows you understand both the theory and the code.

Follow-ups to expect

  • "What if the input has duplicates?" Sort and skip equal siblings, as in the subsets example.

  • "Can you return only the count?" If subproblems repeat, switch to dynamic programming; otherwise keep the search but increment a counter instead of copying.

  • "How deep does the recursion go?" At most the answer length, so the call stack is O(n). Mention it, since a deep stack can overflow in some languages.

  • "Can you stop at the first answer?" Return a boolean from explore and stop looping once it is true.

What changes with seniority

A junior candidate should produce subsets or permutations from the template and get the copy and the undo right. A mid-level candidate handles duplicates with the sorted-sibling rule unprompted, prunes with a bound, and states the complexity as nodes times work per node. A senior candidate also says when backtracking is the wrong tool (a count or an optimum with repeated subproblems belongs to dynamic programming), and estimates whether the search fits the time limit from the input size before writing it.

Mistakes that cost points

  • Recording the shared array instead of a copy. Every result becomes the final, usually empty, state. Write [...current] every time.

  • Undoing only half the choice. If choose sets a flag and pushes, undo must pop and clear the flag.

  • Checking validity only at the leaves. It produces correct answers far too slowly. Validate when you make the choice.

  • Coding before naming the tree. State what a choice is and when an answer is complete; the code follows from those two sentences.

  • Calling the solution "O(n)" because it has one loop. Count the nodes of the tree.

Practice it

Take 15 minutes: write the subsets function from memory, then change it in three ways without restarting: handle duplicates, return only subsets of size k, and return subsets whose sum is even. Say the tree's choices and stopping rule out loud before each change.

Then start a coding interview such as Two Sum and practice saying the brute force and its complexity before you optimize. The habit of counting the work is the same one backtracking relies on. The coding quick start covers the full method for a live round.

Practise this in a mock interview

Try what this lesson covers out loud: the AI interviewer asks one of these questions, follows up, and scores your answer.

Read next

  • Dynamic Programming: From Recursion to a Table

    Recognize a dynamic programming problem, apply a five-step recipe (state, recurrence, base case, order, answer), move from memoization to a table and cut its space, and explain the solution out loud.

    9 min read

  • Intervals and Greedy: Sort First, Then Decide Once

    Merge, insert and count overlapping intervals with a sort-then-sweep template, justify a greedy rule with the exchange argument, and recognize when greedy fails and dynamic programming is needed.

    9 min read

  • Two Pointers

    Recognize when sorted input, in-place edits or a linked list call for two pointers, then apply the opposite-ends, reader-writer and fast-slow shapes and say why each pointer move is safe.

    8 min read

  • Sliding Window

    Spot contiguous-range problems, run fixed and variable windows from one template, decide where to record the answer, and explain why the window breaks once values can be negative.

    8 min read