Skip to content
Work Free practice Coding course Blog Method Results Why me About Enquire Book a call

Practice · Coding

Backtracking

Build a solution one choice at a time, and abandon a branch the moment it cannot succeed.


When it applies

✕ fails: cut solution dead end choose, explore, undo

Backtracking is exhaustive search with an exit: choose, explore, undo. It fits problems that ask for every solution, the number of solutions, or whether any exists, when the choices are small and discrete: include this element or not, which sign, which column.

The running time is set by how early you can prune. The same search that is hopeless when it builds complete candidates and then checks them becomes practical when it checks each partial candidate and stops as soon as one constraint fails.

Signals: "all subsets", "all permutations", "every way to", "place n pieces so that", "can the set be split". When the count is all you need and states repeat, the next step is memoisation, which turns the search into dynamic programming.


The template

Write this from memory. Every problem in this section is a specialisation of it, and most bugs come from deviating without a reason.

def backtrack(state, choices):
    if is_complete(state):
        record(state)
        return
    for c in choices(state):
        if not allowed(state, c):      # prune: never extend a partial solution that already fails
            continue
        apply(state, c)
        backtrack(state, choices)
        undo(state, c)                 # restore exactly what apply changed

Problems

Or sit a timed interview: a fixed window, limited submissions, and a report at the end.