Backtracking

Try, and if it fails, go back · Part of Strategies

Key idea

Practice

6 questions · about 3 min

Explained step by step

Backtracking

Backtracking solves a problem with exhaustive search: from an initial state it tries the possible solutions and keeps each one that meets the conditions. It stops when it finds what it needs or when it has tried everything. It almost always goes depth first, like a tree's preorder: it goes down one branch to the bottom before trying another. Example: finding every node with value 7 in a tree by walking it in preorder.

The name comes from how it works: it tries an option and, if it reaches a state it cannot continue from, it goes back. Going back is not just leaving a function: the state must also be left as it was. If the path is kept in a list path, trying adds the node and, before going back, it is removed. Trying and undoing are inverse operations, like a step forward and a step back.

Backtracking problems share a template. There is a state (state), what has been chosen so far, and some options (choices). First you check whether the state is a solution and, if so, you save it. Then, for each option: if it is valid, you choose it, go on with backtrack and undo it. For each problem only what the state is, what the options are and what is valid change.

There are 6 words that keep coming back in backtracking. Solution: an answer that meets the conditions. Constraint: a condition that limits which solutions count. State: where the search is, with what has been chosen. Attempt: choosing an option and updating the state. Backtrack: undoing the choice. Pruning: skipping paths that cannot work.

Backtracking finds every solution, but it can be very expensive: in the worst case it explores every possibility, and its time can be exponential or factorial. It also uses memory to keep the state at each level of the recursion. Even so, it is the best option when you cannot know in advance which choice works. To speed it up you use pruning or heuristic search, which tries the most promising paths first.

Pruning

Many problems have constraints, and they help to prune: cut a branch as soon as you know it cannot give a valid solution. In example 3 you look for paths to 7 that go through no 3: on reaching a node 3 you go back at once, without looking at its children. That saves useless attempts. If that 3 had 100 nodes below it, pruning saves 100 visits.

Terms in this lesson

Arki, the beaver mascot

Your next interview starts with 5 minutes today.

Free on iOS and Android. Start from zero, no account needed.

Key idea

Try, and if it fails, go back