Skip to the page

Recursion, trees and heaps · mid

Backtracking in JavaScript

Backtracking builds a solution step by step: try a choice, recurse, then undo it. It lists subsets, permutations and combinations, and pruning cuts branches that cannot succeed. In JavaScript, push a copy of the path ([...path]) and undo each push with pop().

The notes

What you must know

  • Template: function dfs(state) { if (done) { out.push(copy); return; } for (choice of choices) { if (!valid) continue; make(choice); dfs(next); undo(choice); } }.
  • Push a COPY of the path ([...path]); pushing path itself gives you many references to one empty array.
  • Subsets: 2^n; permutations: n!; say the output size, it dominates complexity.
  • Combination sum: sort candidates, start index i to avoid duplicates, break when candidate > remaining.
  • Pruning: stop early when the partial answer is already invalid (open < close in parentheses, remaining < 0).
  • Frontend links: generating all valid team selections (Dream11 LLD), word break 'all sentences', solving puzzles in game rounds.
  • Strings are immutable, so passing cur + ch to the next call needs no undo step. With an array path, every push must have a matching pop() after the recursive call.

The red pen

Common traps: mistake → fix

  • Mistake: out.push(path)

    Fix: later undo steps empty it; push [...path].

  • Mistake: Use a visited Set for permutations of values with duplicates

    Fix: sort and skip equal neighbours that were not used.

  • Mistake: Backtracking is the same as DP

    Fix: DP reuses overlapping sub-results; backtracking enumerates.

Easy to hard

Questions interviewers ask, easy to hard

  1. Generate all subsets.
  2. All permutations; what if values repeat?
  3. Combination sum with unlimited reuse.
  4. Generate all valid parentheses of n pairs; how do you prune?

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview