Skip to content
Concept ยท Data Structures and Algorithms

Backtracking explained: the template, N-Queens, subsets and permutations

Younus FardeenBy Younus FardeenUpdated 1 Dec 20269 min read
Short answer

Backtracking builds a solution one choice at a time, and when a partial solution cannot work, it undoes the last choice and tries another. It is depth-first search over a tree of choices with pruning. Use it to list all subsets, permutations or valid placements, such as N-Queens. Its worst case is still exponential.

On this pageWhat backtracking is, in one templateSubsets and permutationsN-Queens: backtracking with real pruningSudoku, and what else fitsComplexity, honestly, and when not to use itFrequently asked questions

Backtracking is the technique behind "generate all" and "place things so that no rule is broken" problems. This page gives one template that fits all of them, then applies it to subsets, permutations, combination sum and N-Queens with code that was run on Python 3.9. It measures what pruning saves on N-Queens and is honest about the cost: backtracking is clever brute force, not a way around exponential growth.

It builds on recursion, because every backtracking function is a recursion. If the problem asks for the best value or a count rather than every solution, you probably want dynamic programming instead; the recursion vs iteration page covers the stack depth that backtracking relies on.

What backtracking is, in one template

Backtracking explores a tree of choices depth first. At each node you choose one option, recurse to decide the rest, then undo the choice so the next option starts from a clean state. Whenever the partial answer already breaks a rule, you stop and go back without exploring below it; that is pruning. Almost every solution fits this shape:

  1. If the partial solution is complete, record a copy of it and return.
  2. For each option available from here: skip it if it breaks a rule (prune).
  3. Choose it: add it to the path and update any tracking state.
  4. Recurse to fill the remaining positions.
  5. Un-choose: remove it from the path and restore the tracking state.

Step 5 is the whole technique. If the recursive call does not leave the state exactly as it found it, later branches will see stale data and the answers will be wrong. Two bugs account for most failed attempts: forgetting to undo a choice, and appending the live path list to the results instead of a copy (path[:]), which turns every stored answer into the same empty list at the end.

Subsets and permutations

Subsets (the power set)

For each element there are two choices, in or out, so n elements give 2^n subsets. The code records every node of the tree, not only the leaves, and the start index stops it picking earlier elements again so no subset appears twice.

def subsets(nums):
    result, path = [], []
    def backtrack(start):
        result.append(path[:])            # every node of the tree is a valid subset
        for i in range(start, len(nums)):
            path.append(nums[i])          # choose
            backtrack(i + 1)              # explore
            path.pop()                    # un-choose
    backtrack(0)
    return result

print(subsets([1, 2, 3]))

Output: [[], [1], [1, 2], [1, 2, 3], [1, 3], [2], [2, 3], [3]]. Eight subsets for three elements.

Permutations

Now order matters and every element is used once, so n elements give n! orderings. A used array is the pruning rule: an element already in the path is skipped.

def permutations(nums):
    result, path, used = [], [], [False] * len(nums)
    def backtrack():
        if len(path) == len(nums):
            result.append(path[:])
            return
        for i in range(len(nums)):
            if used[i]:
                continue                  # prune: item already in this path
            used[i] = True
            path.append(nums[i])
            backtrack()
            path.pop()
            used[i] = False
    backtrack()
    return result

p = permutations([1, 2, 3])
print(len(p), p)

Output: 6 [[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]. If the input contains duplicates, sort it first and skip an element equal to the previous unused one; otherwise you get repeated permutations.

Combination sum: pruning on a sum

Find every combination of the candidates, each reusable any number of times, that adds up to the target. Sorting lets the loop break as soon as a candidate exceeds what remains, because every later one is larger still. This one line of pruning is the difference between a fast solution and a slow one.

def combination_sum(candidates, target):
    candidates.sort()                     # sorted so we can stop early
    result, path = [], []
    def go(start, remaining):
        if remaining == 0:
            result.append(path[:])
            return
        for i in range(start, len(candidates)):
            if candidates[i] > remaining:
                break                     # prune: later numbers are bigger still
            path.append(candidates[i])
            go(i, remaining - candidates[i])   # same number may be reused
            path.pop()
    go(0, target)
    return result

print(combination_sum([2, 3, 6, 7], 7))

Output: [[2, 2, 3], [7]] for candidates 2, 3, 6, 7 and target 7.

N-Queens: backtracking with real pruning

Place n queens on an n x n board so that none shares a row, column or diagonal. Put one queen per row, which removes the row check, and keep three sets: used columns, used r - c diagonals and used r + c diagonals. A square is allowed only if none of the three sets already contains its values. The code counts solutions and also the number of calls to place, so you can see the work done.

def solve_queens(n):
    solutions = []
    cols, diag1, diag2 = set(), set(), set()
    placement = []                        # placement[r] = column of the queen in row r
    nodes = 0
    def place(r):
        nonlocal nodes
        nodes += 1
        if r == n:
            solutions.append(placement[:])
            return
        for c in range(n):
            if c in cols or (r - c) in diag1 or (r + c) in diag2:
                continue                  # prune: this square is attacked
            cols.add(c); diag1.add(r - c); diag2.add(r + c)
            placement.append(c)
            place(r + 1)
            placement.pop()
            cols.remove(c); diag1.remove(r - c); diag2.remove(r + c)
    place(0)
    return solutions, nodes

for n in range(4, 9):
    sols, nodes = solve_queens(n)
    print(n, len(sols), nodes)

sols, _ = solve_queens(6)
print(sols[0])
for c in sols[0]:
    print(" ".join("Q" if i == c else "." for i in range(6)))

Output, as n solutions nodes: 4 2 17, 5 10 54, 6 4 153, 7 40 552, 8 92 2057, then the first solution for n=6, [1, 3, 5, 0, 2, 4], drawn as a board. The solution counts of 2, 10, 4, 40 and 92 for n = 4 to 8 are the well-known ones. For n=6 there are 4 solutions and the search made 153 calls.

How much did pruning save? A search with no pruning tries every assignment of one column per row, which is 6^6 = 46,656 for n=6, and checks each for conflicts. The next block does exactly that.

from itertools import product

def queens_brute(n):                      # no pruning: try every row-to-column assignment
    count = checks = 0
    for cols in product(range(n), repeat=n):
        checks += 1
        if all(abs(cols[i] - cols[j]) != j - i and cols[i] != cols[j]
               for i in range(n) for j in range(i + 1, n)):
            count += 1
    return count, checks

print(queens_brute(6))                    # compare with the pruned search's node count

Output: (4, 46656). Same 4 answers, but 46,656 full boards examined against 153 recursive calls. The board is a 6 x 6; at 8 x 8 the unpruned count is 8^8 = 16,777,216 against 2,057 calls above. Pruning is what makes backtracking usable at all.

Sudoku, and what else fits

Sudoku is the same template: pick the next empty cell, try digits 1 to 9 that do not appear in its row, column or box, recurse, and undo on failure. A bare version solves most newspaper puzzles quickly. Hard ones need better pruning: choose the empty cell with the fewest legal digits first, and keep row, column and box sets so legality is checked in constant time rather than by scanning.

ProblemChoice at each stepPruning ruleSolution count
SubsetsInclude or exclude an elementNone needed (every node is valid)2^n
PermutationsNext unused elementSkip used elementsn!
Combination sumNext candidate, reuse allowedStop when candidate > remainingDepends on input
N-QueensColumn for this rowColumn or diagonal already attacked2, 10, 4, 40, 92 for n = 4 to 8
SudokuDigit for next empty cellDigit already in row, column or boxUsually 1
Word search in a gridNext neighbouring cellCell already used or letter differsDepends on input

Complexity, honestly, and when not to use it

Pruning cuts branches but does not change the worst case. Subsets take O(n x 2^n) because each of 2^n subsets is copied out at up to n elements. Permutations take O(n x n!). N-Queens is bounded by n! placements without pruning and is far smaller in practice, but the search is still exponential as n grows. Memory is O(n) for the path and tracking sets, plus whatever you store in the results.

Use that to decide whether it will finish: 2^20 is about a million and fine, 2^30 is about a billion and slow in Python, and 12! is 479 million. Rule of thumb: backtracking is for inputs of roughly 20 items or fewer, or for tightly constrained problems like Sudoku where pruning removes nearly all branches.

  • Need only the count, the best value or a yes/no, and sub-problems repeat: use dynamic programming, not backtracking.
  • A locally best choice is provably safe: a greedy algorithm is faster.
  • The input is large and you need every solution anyway: the output itself is exponential, so no algorithm will be fast.
  • You are likely to hit Python's default recursion limit of 1000: depth equals the number of choices, so it is fine for these examples but not for a path of thousands of steps.

Backtracking problems are common in coding rounds; the pattern list in DSA interview questions shows where they sit, and coding practice websites lists places to get more problems.

Frequently asked questions

What is backtracking in simple words?

Backtracking is trying a choice, continuing, and undoing the choice if it leads nowhere, then trying the next option. It is recursion that explores every possibility but abandons any branch as soon as it breaks a rule. Solving a maze by retracing your steps at a dead end is the everyday picture.

What is the difference between backtracking and recursion?

Recursion is a general technique where a function calls itself. Backtracking is a specific use of it: depth-first search over choices with an undo step and pruning. Every backtracking solution is recursive, but most recursive functions, such as factorial, do not backtrack.

What is the difference between backtracking and brute force?

Brute force generates every complete candidate and then tests it. Backtracking tests as it builds and abandons a partial candidate the moment it fails, so whole groups of candidates are never generated. For 6-Queens, brute force examined 46,656 boards while backtracking made 153 calls, with the same 4 answers.

How many solutions does the N-Queens problem have?

There are 2 solutions for 4 queens, 10 for 5, 4 for 6, 40 for 7 and 92 for 8, as counted by the code above. The count does not grow smoothly; 6 has fewer than 5. For 8 queens, the 92 solutions include rotations and reflections of each other.

What is the time complexity of backtracking?

It depends on the problem and is usually exponential or factorial: O(2^n) for subsets, O(n!) for permutations, and an exponential worst case for N-Queens and Sudoku. Pruning shrinks the real work, often dramatically, but it rarely changes the worst-case bound.

When should I use backtracking instead of dynamic programming?

Use backtracking when the question asks for every solution, or when constraints must be checked as you build, such as N-Queens or Sudoku. Use dynamic programming when you want a count or an optimum and the same sub-problems appear repeatedly, so caching avoids re-solving them.

Learn this with mentors

Programmes for builders and engineers with admissions open: live classes, mentors and project work.

Continue learning

Explainer

What is recursion?

Base case, call stack and examples, with code in three languages.

5 min read
Explainer

Dynamic programming explained

Memoization vs tabulation and five solved examples.

4 min read
Concept

Recursion vs iteration

Differences, same problems both ways, Python limits and when to choose each

7 min read