The backtracking pattern

Master the backtracking pattern to systematically explore all possibilities in combinatorial problems. Learn the core template, common pitfalls, and how to solve classic interview questions like Permutations and N-Queens.

intermediate13 min readBy CureBugs EditorialUpdated 5 Nov 2026

Backtracking is a systematic algorithmic technique for solving problems recursively by trying to build a solution incrementally, one piece at a time. Whenever the algorithm realizes that the current path cannot possibly lead to a valid solution, it abandons it ("backtracks") and tries the next available option. Think of it as an optimized brute-force search: instead of generating all possible configurations and then checking if they are valid, backtracking prunes the search space early, saving massive amounts of computation time. In interviews at top tech companies, backtracking is the go-to pattern for combinatorial problems.

When to use this pattern

Recognizing a backtracking problem is usually straightforward if you pay attention to the problem statement and the constraints. Look for these strong signals:

  1. Keywords asking for exhaustive results: If a problem asks you to "find all possible combinations", "return all permutations", "generate all valid subsets", or "find all paths", it is almost certainly a backtracking problem.
  2. Decision-making puzzles: Problems like Sudoku, N-Queens, or solving a maze require you to make a choice, see if it works, and undo it if it doesn't.
  3. Very small constraints: This is the biggest giveaway. Backtracking algorithms usually have exponential $O(2^N)$ or factorial $O(N!)$ time complexities. If you see input constraints like $N \le 15$ or $N \le 20$, the interviewer expects an exhaustive search. A polynomial time algorithm like $O(N^2)$ would easily handle $N = 1000$, so an unusually small $N$ screams "backtracking".

The core idea

Backtracking can be visualized as traversing a state-space tree. Each node in the tree represents a partial solution. The edges represent the choices you can make to extend that solution.

The core paradigm is Choose, Explore, Unchoose:

  1. Choose: Make a choice to add an element to your current path.
  2. Explore: Recursively call the function to continue building the solution from this new state.
  3. Unchoose (Backtrack): Remove the element you just added so you can try the next available choice at that level.

Let's visualize generating all subsets of the array [1, 2]:

When the algorithm reaches [1, 2], it records the result, then backtracks up to [1], and tries the next option (excluding 2) to reach [1].

Template

Almost all backtracking problems can be solved using a standard template. Memorizing this structure will give you a massive advantage in interviews.

def solve(input_data):
    res = []
    
    def backtrack(path, options):
        # 1. Base Case: Check if the current path is a valid solution
        if is_valid_solution(path):
            res.append(path[:]) # Deep copy the path!
            return
            
        # 2. Iterate through all possible choices
        for choice in options:
            if not is_valid_choice(choice):
                continue # Prune invalid paths
                
            # 3. Choose
            path.append(choice)
            
            # 4. Explore
            backtrack(path, updated_options)
            
            # 5. Unchoose (Backtrack)
            path.pop()
            
    backtrack([], initial_options)
    return res

Worked examples

Let's apply this template to three classic interview problems, increasing in difficulty.

Example 1: Permutations

Problem: Given an array nums of distinct integers, return all the possible permutations. You can return the answer in any order.

Approach: To generate permutations, we need to pick elements one by one. Since order matters in permutations ([1,2,3] is different from [2,1,3]), we always iterate through the entire array from index 0. However, we cannot reuse elements we have already picked in the current path. We can use a boolean used array to keep track of which elements are currently in our path.

def permute(nums):
    res = []
    used = [False] * len(nums)
    
    def backtrack(path):
        # Base case: path length equals nums length
        if len(path) == len(nums):
            res.append(path[:])
            return
            
        for i in range(len(nums)):
            if used[i]: 
                continue # Skip already used elements
                
            # Choose
            used[i] = True
            path.append(nums[i])
            
            # Explore
            backtrack(path)
            
            # Unchoose
            path.pop()
            used[i] = False
            
    backtrack([])
    return res

Complexity:

  • Time Complexity: $O(N \cdot N!)$. There are $N!$ permutations, and for each permutation, we take $O(N)$ time to copy the path into our result array.
  • Space Complexity: $O(N)$ for the recursion stack and the used array (excluding the space required to hold the output).

Example 2: Combination Sum

Problem: Given an array of distinct integers candidates and a target integer target, return a list of all unique combinations of candidates where the chosen numbers sum to target. You may choose the same number an unlimited number of times.

Approach: Unlike permutations, order does not matter here ([2,2,3] is the same combination as [3,2,2]). To avoid generating duplicate combinations, we must enforce an artificial order. We do this by passing a start index to our recursive function. When we are at index i, our next choices can only be from index i onwards. Because we can reuse elements, the recursive call will pass i as the next start index, not i + 1.

def combinationSum(candidates, target):
    res = []
    
    def backtrack(start, current_sum, path):
        if current_sum == target:
            res.append(path[:])
            return
        if current_sum > target:
            return # Prune: we exceeded the target
            
        for i in range(start, len(candidates)):
            path.append(candidates[i])
            # We pass 'i' as start because we can reuse the same element
            backtrack(i, current_sum + candidates[i], path)
            path.pop()
            
    backtrack(0, 0, [])
    return res

Complexity:

  • Time Complexity: $O(N^{\frac{T}{M}})$, where $N$ is the number of candidates, $T$ is the target value, and $M$ is the minimum value among the candidates. The maximum depth of the recursion tree is $\frac{T}{M}$.
  • Space Complexity: $O(\frac{T}{M})$ for the recursion stack.

Example 3: N-Queens

Problem: The n-queens puzzle is the problem of placing n queens on an n x n chessboard such that no two queens attack each other. Return all distinct solutions.

Approach: This is a classic state-space problem. We place queens row by row. For a given row, we try placing a queen in each column. To efficiently check if a placement is valid, we maintain three sets (or boolean arrays): one for the columns, one for the main diagonals, and one for the anti-diagonals.

  • A cell (r, c) shares a main diagonal with other cells if their difference r - c is constant.
  • A cell (r, c) shares an anti-diagonal with other cells if their sum r + c is constant.
def solveNQueens(n):
    res = []
    board = [["."] * n for _ in range(n)]
    
    cols = set()
    pos_diag = set() # r + c
    neg_diag = set() # r - c
    
    def backtrack(r):
        if r == n:
            res.append(["".join(row) for row in board])
            return
            
        for c in range(n):
            if c in cols or (r + c) in pos_diag or (r - c) in neg_diag:
                continue
                
            # Choose
            cols.add(c)
            pos_diag.add(r + c)
            neg_diag.add(r - c)
            board[r][c] = "Q"
            
            # Explore
            backtrack(r + 1)
            
            # Unchoose
            cols.remove(c)
            pos_diag.remove(r + c)
            neg_diag.remove(r - c)
            board[r][c] = "."
            
    backtrack(0)
    return res

Complexity:

  • Time Complexity: $O(N!)$. For the first row we have $N$ choices, for the second roughly $N-2$, and so on. This bounds the time complexity to factorial.
  • Space Complexity: $O(N^2)$ to store the board state, or $O(N)$ if we only consider the recursion stack and sets.

Variations and pitfalls

1. The "List of Empty Lists" Bug

This is the single most common mistake candidates make in interviews.

The Fix: Always make a deep copy or clone of the path before appending it to the result.

  • Python: res.append(path[:]) or res.append(list(path))
  • Java: res.add(new ArrayList<>(path))
  • JS: res.push([...path])
  • C++: res.push_back(path) (C++ handles this automatically as push_back makes a copy by value).

2. Permutations vs. Combinations vs. Subsets

Understanding the subtle differences in the for loop of the template is critical.

Problem TypeOrder Matters?Loop Start IndexState Tracking Needed?
PermutationsYes ([1,2] $\neq$ [2,1])Always 0Yes (e.g., used array)
CombinationsNo ([1,2] $=$ [2,1])start (passed in recursion)No (handled by start index)
SubsetsNostart (passed in recursion)No (handled by start index)

3. Inefficient String Concatenation

In problems where the path is a string (like generating valid parentheses or palindromic partitions), avoid doing path = path + "a" inside the loop if you can help it. String concatenation creates a completely new string in memory every time, changing the time complexity. Instead, use a mutable array (like a list in Python, StringBuilder in Java, or vector<char> in C++) and join them at the base case.

Practice checklist

To truly master backtracking, you need to build muscle memory for the template and learn how to adapt the "Explore" and "Pruning" steps. Start with these fundamental problems before moving to harder grid-based puzzles.

  1. Subsets (Classic start index problem)
  2. Combinations (Fixed length subsets)
  3. Permutations (Classic used array problem)
  4. Combination Sum II (Handling duplicates in the input array)
  5. Word Search (Backtracking on a 2D grid)
  6. Palindrome Partitioning (Backtracking with string manipulation)

Once you are comfortable with these, you will be well-prepared for any backtracking question an interviewer throws your way.

Mock interview

Solve one like this with an interviewer watching

Getting the answer alone is half the round. The other half is clarifying the problem, explaining your approach, coding while you talk and handling the follow-up. Try it on a problem you haven't seen.

  • A timed problem in a real editor, judged on hidden tests
  • Hints if you ask, and they count against you like they would in the room
  • A scored report that quotes your answers and says what to fix
Start a mock coding round Voice or text. Pause whenever you need to.

Applying somewhere? Start with the company filled in

Go deeper elsewhere

The best material we've found on these topics.

Practise this

Reading builds understanding. Practice makes it stick.

Keep reading

All articles
The backtracking pattern · CureBugs