Algorithms · Visualized

Backtracking

Backtracking

Build candidates incrementally and abandon ("prune") a branch the moment it can no longer lead to a valid answer.

Big-O: Try a choice, recurse, undo it, try the next. Depth-first search over the space of partial solutions.

📖 Family Introduction

Backtracking

Explore every candidate path, abandon dead ends early, and undo cleanly.

Backtracking is exhaustive search with pruning: build a candidate solution one decision at a time, and as soon as a partial choice can no longer lead to a valid solution, undo it and try the next option. The "un-choose" step is what defines the technique — state is restored exactly, so sibling branches explore from a clean slate. Worst-case time is exponential in the decision count, but constraint checks that prune whole subtrees make real problems (N-Queens, Sudoku) tractable.

The general recipe

  1. Frame the search as a tree of decisions (position 0 chooses, position 1 chooses, …).
  2. Choose: extend the partial solution with the next candidate.
  3. Constrain: check validity of the partial state; if invalid, stop descending (prune).
  4. Recurse deeper to enumerate completions of this choice.
  5. Un-choose: restore all mutated state (remove marks, pop from the path) before trying the next candidate.

Vocabulary you'll meet everywhere here

Partial solution
the decisions made so far along the current path
Pruning
abandoning a branch the moment it violates a constraint
State restore
undoing mutations (used flags, board marks) after returning from a branch
Decision tree
the implicit tree of all choice sequences backtracking walks
Deduplication
sorting candidates and skipping equal values at the same tree level to avoid duplicate answers

Where this family shows up

  • Permutations, subsets, combinations and their "no duplicate" variants
  • Constraint puzzles: N-Queens, Sudoku, word search, rat maze, knight’s tour, graph coloring
  • Any "generate all valid X" request where validity can be checked on partial states

Common pitfalls

  • Forgetting to undo a mutation (visited flag, placed queen) leaks state across branches
  • Checking constraints only at the end instead of pruning early turns tractable puzzles into timeouts
  • Duplicate outputs when input has repeated values — sort and skip same-valued candidates at one level
  • Confusing "explore" order with "answer" order: results are collected at leaves/base cases, not at every node
Python · Backtracking in Code
def subsets(a):
    out = []
    def build(i, cur):
        if i == len(a):
            out.append(cur[:])
            return
        build(i + 1, cur)
        cur.append(a[i])
        build(i + 1, cur)
        cur.pop()
    build(0, [])
    return out

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits

Keep the momentum going

Step through a related structure, pattern or course — the ideas reinforce each other and stick faster.