Quick reference
Backtracking is a way to solve problems by building a solution one choice at a time and undoing the last choice (that's the "backtrack") as soon as it can't lead to a valid answer, then trying the next option. It's how you generate every subset or permutation, place N queens on a chessboard, or solve a Sudoku.
When to use it:
- The problem asks for every arrangement, combination, subset, or permutation that follows some rules, or for any one that does.
- You can build an answer step by step, and you can tell partway through when a partial answer is already broken.
- The input is small (often 20 items or fewer), since the number of possibilities grows exponentially.
The template:
- Choose an option and add it to the partial solution.
- Explore: recurse to fill in the rest.
- Un-choose: remove the option again, so the next option starts from the same state.
- Prune: skip any option that already breaks a rule, along with everything that would have been built on top of it.
Cost:
- Usually exponential time. There are 2^n subsets and n! permutations of n items, so listing them takes O(n · 2ⁿ) and O(n · n!) time. Pruning often cuts the work by a lot in practice, but it doesn't change the worst case. Extra space is O(n) for the recursion and the partial solution, plus whatever the output takes.
How Backtracking Works
A backtracking algorithm keeps a partial solution (often called the path) and grows it one choice at a time. At each step it asks three questions:
- Is the path a complete solution? If so, record it.
- What choices could come next? Try each one in turn.
- Does this choice break a rule? If so, skip it. There's no point exploring anything built on top of a choice that's already invalid.
Here's the template that nearly every backtracking solution follows:
The un-choose step is what makes it backtracking. There's only one path, and every call shares it, so before we try the next choice, we have to put the path back exactly the way we found it.
The recursion tree
It helps to picture the calls as a tree. The root is the empty path, each child adds one more choice, and each leaf is either a complete solution or a dead end. Backtracking walks this tree depth first: it follows one branch all the way down, then backs up to the most recent spot where there's still an untried choice.
Pruning cuts off a whole subtree at once. If the first two queens on a chessboard already attack each other, every board that starts with those two queens is invalid too, so we skip all of them with a single check.
Example: Generate All Subsets
Problem: given an array of distinct items, return every subset. Say a bakery offers three toppings and we want every topping combination a customer could order, including no toppings at all. With the toppings numbered 1, 2, and 3, there are 2 × 2 × 2 = 8 subsets, since each topping is either in or out.
Every path is a valid subset here, so we record each one as soon as we reach it. To avoid listing the same subset twice (like [1, 2] and [2, 1]), each call only adds items that come after the last item it added:
Here's the recursion tree. Each line is one call, showing the path it records, and the lines indented under it are the calls it makes:
-
[ ]
-
[1]
-
[1, 2]
- [1, 2, 3]
- [1, 3]
-
[1, 2]
-
[2]
- [2, 3]
- [3]
-
[1]
The tree has exactly one node per subset, and the order they're recorded in is the order we'd reach them walking the tree depth first: [ ], [1], [1, 2], [1, 2, 3], [1, 3], [2], [2, 3], [3].
Example: Generate All Permutations
Problem: return every ordering of an array of distinct items. For [1, 2, 3] there are 3! = 6.
This time a path is only complete once it holds every item, and the next choice can be any item that isn't in the path yet. We keep a "used" flag for each item, so we have to undo two things when we un-choose: take the item off the path, and mark it unused again:
Here's how the path changes as the search runs. Notice that every "choose" gets a matching "un-choose" on the way back up:
| Step | Action | Path | Recorded |
|---|---|---|---|
| 1 | Choose 1 | [1] | |
| 2 | Choose 2 | [1, 2] | |
| 3 | Choose 3. Every item is used, so the path is complete. | [1, 2, 3] | [1, 2, 3] |
| 4 | Un-choose 3. No other unused items to try here. | [1, 2] | |
| 5 | Un-choose 2 | [1] | |
| 6 | Choose 3 | [1, 3] | |
| 7 | Choose 2. The path is complete. | [1, 3, 2] | [1, 3, 2] |
| 8 | Un-choose 2, then 3, then 1 | [ ] | |
| 9 | Choose 2, and keep going the same way | [2] |
Our practice question Recursive String Permutations asks for every permutation of a string. You can solve it with this same choose, explore, un-choose pattern, and the question also walks through a different recursive approach.
Pruning in Action: The N-Queens Problem
Problem: place n queens on an n × n chessboard so that no two attack each other. A queen attacks every square in its row, its column, and both of its diagonals.
Since no two queens can share a row, each row gets exactly one queen. So we fill the board one row at a time, and the choice at each step is which column to put that row's queen in. Before placing a queen, we check whether an earlier queen already attacks that square:
- Same column: we keep track of which columns are taken.
-
Same diagonal: every square on a "\" diagonal
has the same value of
row - col, and every square on a "/" diagonal has the same value ofrow + col. So we keep track of which of those values are taken, too.
That makes each check O(1). If the square is attacked, we prune: we skip it, and with it, every board that would have had a queen there.
Tracing 4 queens
Here's the search for n = 4 up to the first solution. Rows and columns are numbered from 0, and "Queens" lists the column of the queen in each row so far, so [0, 2] means row 0's queen is in column 0 and row 1's is in column 2.
| Step | Row | What happens | Queens |
|---|---|---|---|
| 1 | 0 | Column 0 is free. Place a queen. | [0] |
| 2 | 1 | Prune column 0 (same column) and column 1 (same diagonal). Place a queen in column 2. | [0, 2] |
| 3 | 2 | All 4 columns are attacked. Dead end: backtrack and remove row 1's queen. | [0] |
| 4 | 1 | Try the next column, 3. It's free. Place a queen. | [0, 3] |
| 5 | 2 | Prune column 0. Place a queen in column 1. | [0, 3, 1] |
| 6 | 3 | All 4 columns are attacked. Dead end: remove row 2's queen. | [0, 3] |
| 7 | 2 | Columns 2 and 3 are attacked too. Dead end: remove row 1's queen. | [0] |
| 8 | 1 | No columns left to try. Dead end: remove row 0's queen. | [ ] |
| 9 | 0 | Try the next column, 1. Place a queen. | [1] |
| 10 | 1 | Prune columns 0, 1, and 2. Place a queen in column 3. | [1, 3] |
| 11 | 2 | Column 0 is free. Place a queen. | [1, 3, 0] |
| 12 | 3 | Prune columns 0 and 1. Place a queen in column 2. Every row has a queen: that's a solution! | [1, 3, 0, 2] |
We found a solution after placing just 8 queens. A brute-force search that put one queen in each row and only checked full boards would have up to 44 = 256 boards to check. The full backtracking search, which finds both 4-queen solutions, places a queen only 16 times.
Here's the code. It returns every solution, each written as the column of the queen in each row, like [1, 3, 0, 2]:
The number of solutions for n = 1 through 8 is 1, 0, 0, 2, 10, 4, 40, and 92. For the classic 8 × 8 board, there are 88 = 16,777,216 ways to put one queen in each row, but the backtracking search places a queen only 2,056 times (and checks 15,720 squares) to find all 92 solutions.
The same idea solves Sudoku: find the first empty cell, try each digit from 1 to 9 that isn't already in its row, column, or 3 × 3 box, recurse, and clear the cell again if nothing works.
Backtracking Time and Space Complexity
Backtracking takes time roughly proportional to the number of nodes in its recursion tree, times the work done at each node. For problems that list every answer, the number of answers alone is exponential:
| Problem | Number of answers | Time | Extra space (not counting the output) |
|---|---|---|---|
| All subsets | 2^n | O(n · 2ⁿ): one node per subset, and copying each one takes up to O(n) | O(n) |
| All permutations | n! | O(n · n!): n! complete paths, each copied in O(n), and fewer than 3 × n! partial paths along the way, each looping over n items | O(n) |
| N-Queens | Grows very fast (92 for n = 8) | At most n! ways to fill the rows using different columns, so O(n · n!) is a safe upper bound. The diagonal checks make the real number of steps far smaller. | O(n) |
The extra space is O(n) because the recursion only goes n levels deep, and the path never holds more than n items. The output itself can be much bigger: all subsets of n items take O(n · 2ⁿ) space to store.
Why pruning doesn't fix the worst case
Pruning skips branches that can't lead to an answer, and on real inputs that's often most of the tree. But it can't make the algorithm fast in general:
- If you have to list every answer, you can't go faster than the number of answers. There's nothing to prune when generating subsets, because every path is valid.
- Some inputs barely prune at all. When the rules only fail near the bottom of the tree, the search still visits almost every node before it finds out.
- Many backtracking problems are believed to have no fast algorithm at all, like solving Sudoku on bigger boards or deciding whether a graph can be colored with 3 colors (both are NP-complete). So we describe the running time by its exponential worst case, and treat pruning as a way to make typical inputs fast.
Backtracking vs. Brute Force vs. Dynamic Programming
| Brute force | Backtracking | Dynamic programming | |
|---|---|---|---|
| How it works | Generates every complete candidate, then checks each one | Builds candidates one choice at a time and abandons a partial candidate as soon as it breaks a rule | Splits the problem into smaller subproblems, solves each distinct one once, and reuses the answers |
| Good at | Tiny inputs, or as a first draft and a way to check a faster solution | Listing every valid answer, or finding one, when rules can be checked partway through | Counting the answers or finding the best one, when the same subproblems come up again and again |
| Typical time | Exponential, always the full amount | Exponential in the worst case, often much less with pruning | The number of distinct subproblems times the work per subproblem, which is often polynomial |
| Example | Check all n^n ways to put one queen in each row | N-Queens, Sudoku, list every subset that adds up to a target | Count the ways to make change, or decide whether any subset adds up to a target |
Backtracking is brute force, just smarter about it: it checks the rules as it goes instead of only at the end.
The line between backtracking and dynamic programming is whether subproblems overlap. Take "can any subset of these numbers add up to 50?" A backtracking search decides "include it or not" for each number, which is up to 2^n paths. But all the search needs to know at any point is which number it's on and how much of the 50 is left, and lots of different paths reach the same pair. Saving the answer for each pair the first time (memoization) turns the search into dynamic programming. If the numbers are all positive, there are only about n × 51 different pairs to solve.
So: if the problem asks you to list every answer, use backtracking, since the output itself can be exponential. If it asks for a count, a yes or no, or the best answer, and the rest of the search depends only on a small amount of state, try dynamic programming.
Backtracking vs. DFS
Backtracking is a depth-first search of the tree of choices, so the two are closely related. The difference shows up when you search a graph or a grid. A plain DFS marks each node visited and never unmarks it, so it reaches every node once. Backtracking unmarks a node when it backs up, so the same node can be part of many different paths. That's what you need for problems like "does this word appear in a grid of letters?" A cell can't be used twice in one path, but a different path is allowed to use it.
Common Backtracking Mistakes
-
Forgetting to un-choose. Every change you make before the recursive call has to be undone after it: remove the item from the path, clear the "used" flag, take the queen's column and diagonals back out. Miss one, and later branches start from the wrong state and quietly skip valid answers.
-
Recording the path itself instead of a copy. There's only one path, and it keeps changing as the search runs:
// wrong: path is one list that we keep changing. this saves a reference // to it, so every entry in result ends up being the same (empty) list. result.add(path); // right: save a copy of path as it is right now result.add(new ArrayList<>(path));With the wrong line, the subsets example returns eight references to the same path, which is empty by the time the search finishes: [[ ], [ ], [ ], [ ], [ ], [ ], [ ], [ ]].
-
Checking the rules only at the end. If you build complete candidates and only then check them, you've written brute force. Check each choice as you make it, so a bad choice cuts off its whole subtree.
-
Duplicate answers when the input has duplicates. For [1, 2, 2], the subsets code above returns [1, 2] twice. Sort the input first, then skip an item when it equals the item just before it at the same level of the tree. For subsets, that means skipping
items[i]wheni > startanditems[i] == items[i - 1]. For permutations, skip it whenitems[i] == items[i - 1]anditems[i - 1]isn't currently used. -
Not stopping early when one answer is enough. If the problem asks whether any solution exists (or for just one, like a Sudoku solver), have the recursive call return true as soon as it finds one, and return immediately when a call returns true.
-
Using backtracking when the subproblems overlap. If the problem only wants a count or the best value, and many paths reach the same state, an exponential search can often become a much faster one with memoization or a dynamic programming table.
Classic Backtracking Problems
- Subsets and permutations, as above.
- Combinations: every way to choose k of n items. Use the subsets code, but only record paths of length k, and stop going deeper once a path is that long.
- Combination sum: every set of numbers that adds up to a target. Prune as soon as the running total goes over the target (if all the numbers are positive).
- Generate valid parentheses: every balanced string of n pairs. Add "(" while there are fewer than n of them, and only add ")" when there are more "(" than ")" so far.
- Letter combinations of a phone number: one choice per digit, from the letters on that key.
- N-Queens and Sudoku: place pieces or digits one at a time, pruning any that break a rule.
- Word search: find a word in a grid of letters by walking from cell to cell, marking a cell used while it's on the path and unmarking it when you back up.
- Palindrome partitioning: every way to cut a string into pieces that are all palindromes. Only cut off a prefix if it's a palindrome.
Practice: Recursive String Permutations. For more on the recursion underneath all of these, see our recursion guide.
Backtracking interview questions to practice
Each one walks you through a real coding interview problem one hint at a time.
Your first 3 questions are free. Just sign in, no credit card.
See also:
Interview coming up?
Get the free 7-day email crash course. You'll learn how to think algorithmically, so you can break down tricky coding interview questions.
No prior computer science training necessary—we'll get you up to speed quickly, skipping all the overly academic stuff.
No spam. One-click unsubscribe whenever.
You're in! Head over to your email inbox right now to read day one!
Interview Cake