Pattern

Backtracking

Build a candidate choice by choice, undoing a choice and trying the next one as soon as it can't lead anywhere valid.

What it is

Backtracking explores a tree of partial choices — the next element to include, the next cell to step to, the next digit's letter — and abandons a branch the moment it violates a constraint or completes a valid answer, then undoes the last choice and tries the next option at that level. It's exhaustive search with early pruning: you're still visiting every valid possibility (and often many that get cut short), but you never build a complete invalid answer only to throw it away. The technique itself is simple recursion plus "undo state on the way back up"; the actual work is in choosing what state to track and where the constraint check goes.

When it applies

Tells in the problem

The classic mistake

A telltale bug shape: marking a board cell used, or appending to a running path, and then moving on to try the next choice without removing that mark or popping that element first. The bug is invisible on the first branch explored (everything looks right until the function backs out), and only surfaces once a sibling branch runs and finds cells or elements still marked from a path that's no longer active. Guard against it by writing the "undo" line immediately after writing the "do" line, before you fill in what happens in between, so cleanup can never be forgotten by the time you add the recursive call.

Questions to start with

All 11 backtracking questions

Problem statement, examples and hints are free on every page; the worked approach, solution and tests are in the company guides.

Free starter pack

13 must-tier questions with full solutions

Sign in with an email — no purchase — and read them in the full reader.

No password, no spam. One sign-in email; you can read the pack in the full reader.