Backtracking

In short: Backtracking is a way to solve problems by building a solution one choice at a time and undoing the last choice as soon as it can't lead to a valid answer, then trying the next option. Nearly every backtracking solution follows the same choose, explore, un-choose template, and pruning skips whole branches that already break a rule. It usually takes exponential time, like O(n · 2^n) to list all subsets or O(n · n!) to list all permutations.

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:

  1. Is the path a complete solution? If so, record it.
  2. What choices could come next? Try each one in turn.
  3. 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:

backtrack(path): if path is a complete solution: record a copy of path return for each choice that could come next: if the choice breaks a rule: skip to the next choice # prune this whole branch add the choice to path # 1. choose backtrack(path) # 2. explore remove the choice from path # 3. un-choose

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:

import java.util.ArrayList; import java.util.List; public static List<List<Integer>> subsets(int[] items) { List<List<Integer>> result = new ArrayList<>(); backtrack(items, 0, new ArrayList<>(), result); return result; } private static void backtrack(int[] items, int start, List<Integer> path, List<List<Integer>> result) { // every path is a valid subset, so record a copy of it result.add(new ArrayList<>(path)); // try adding each item that comes after the last one we added for (int i = start; i < items.length; i++) { path.add(items[i]); // 1. choose items[i] backtrack(items, i + 1, path, result); // 2. explore every subset that starts with path path.remove(path.size() - 1); // 3. un-choose items[i] before trying the next one } } // subsets(new int[] {1, 2, 3}) returns // [[], [1], [1, 2], [1, 2, 3], [1, 3], [2], [2, 3], [3]]

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]
    • [2]
      • [2, 3]
    • [3]

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:

import java.util.ArrayList; import java.util.List; public static List<List<Integer>> permutations(int[] items) { List<List<Integer>> result = new ArrayList<>(); boolean[] used = new boolean[items.length]; // used[i] is true while items[i] is in path backtrack(items, used, new ArrayList<>(), result); return result; } private static void backtrack(int[] items, boolean[] used, List<Integer> path, List<List<Integer>> result) { // base case: every item is in path, so it's a complete permutation if (path.size() == items.length) { result.add(new ArrayList<>(path)); return; } for (int i = 0; i < items.length; i++) { if (used[i]) { continue; // skip items that are already in path } used[i] = true; // 1. choose items[i] for the next spot path.add(items[i]); backtrack(items, used, path, result); // 2. explore every way to fill the rest path.remove(path.size() - 1); // 3. un-choose items[i] used[i] = false; } } // permutations(new int[] {1, 2, 3}) returns // [[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]

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 of row + 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]:

import java.util.ArrayList; import java.util.List; public static List<List<Integer>> solveNQueens(int n) { List<List<Integer>> solutions = new ArrayList<>(); List<Integer> queens = new ArrayList<>(); // queens.get(row) is the column of the queen in that row boolean[] usedColumns = new boolean[n]; boolean[] usedDiagonals = new boolean[2 * n - 1]; // squares on the same "\" diagonal share row - col boolean[] usedAntiDiagonals = new boolean[2 * n - 1]; // squares on the same "/" diagonal share row + col placeQueen(0, n, queens, usedColumns, usedDiagonals, usedAntiDiagonals, solutions); return solutions; } private static void placeQueen(int row, int n, List<Integer> queens, boolean[] usedColumns, boolean[] usedDiagonals, boolean[] usedAntiDiagonals, List<List<Integer>> solutions) { // base case: every row has a queen, so this is a solution if (row == n) { solutions.add(new ArrayList<>(queens)); return; } for (int col = 0; col < n; col++) { int diagonal = row - col + n - 1; // shifted so it's never negative int antiDiagonal = row + col; // prune: skip squares an earlier queen already attacks if (usedColumns[col] || usedDiagonals[diagonal] || usedAntiDiagonals[antiDiagonal]) { continue; } // 1. choose: put a queen at (row, col) queens.add(col); usedColumns[col] = true; usedDiagonals[diagonal] = true; usedAntiDiagonals[antiDiagonal] = true; // 2. explore: fill in the rows below placeQueen(row + 1, n, queens, usedColumns, usedDiagonals, usedAntiDiagonals, solutions); // 3. un-choose: take the queen back off queens.remove(queens.size() - 1); usedColumns[col] = false; usedDiagonals[diagonal] = false; usedAntiDiagonals[antiDiagonal] = false; } } // solveNQueens(4) returns [[1, 3, 0, 2], [2, 0, 3, 1]] // solveNQueens(n).size() for n = 1 through 8: 1, 0, 0, 2, 10, 4, 40, 92

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] when i > start and items[i] == items[i - 1]. For permutations, skip it when items[i] == items[i - 1] and items[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.

Frequently Asked Questions

What is backtracking?

Backtracking is a way to solve problems by building a solution one choice at a time and undoing the last choice as soon as it can't lead to a valid answer, then trying the next option. It's used to generate subsets and permutations and to solve constraint puzzles like N-Queens and Sudoku.

How does a backtracking algorithm work?

It follows a choose, explore, un-choose template: add an option to the partial solution, recurse to fill in the rest, then remove the option so the next one starts from the same state. Options that already break a rule are skipped, which prunes everything that would have been built on top of them.

What is the time complexity of backtracking?

Usually exponential. Listing all subsets of n items takes O(n · 2^n) time and listing all permutations takes O(n · n!), because that's how many answers there are and each one takes O(n) to copy. Pruning can skip large parts of the search in practice, but it doesn't improve the worst case.

What's the difference between backtracking and brute force?

Brute force builds every complete candidate and checks each one at the end. Backtracking checks the rules while it builds each candidate and abandons a partial one as soon as it breaks a rule, which skips every candidate that would have started the same way.

What's the difference between backtracking and dynamic programming?

Backtracking explores choices to list every valid answer or to find one. Dynamic programming is for counting answers or finding the best one when the same subproblems come up again and again, so it solves each subproblem once and reuses the result. If a backtracking search keeps reaching the same state, memoization can turn it into dynamic programming.

Is backtracking the same as DFS?

Backtracking is a depth-first search of the tree of choices. The difference is that a plain DFS on a graph marks nodes visited for good, while backtracking undoes its choices when it backs up, so the same node or grid cell can be part of many different paths.

Reviewed by Stephen Cognetta, CEO of Aced. Last updated: December 4, 2026

. . .