cswork / templatesOpen the Line 500 list

STOP 21 · BACKTRACKING

Constraint Search and Pruning

N-Queens: prune by column and both diagonals O(n!) worst case

Contest ratings Rating 1720–Rating 1882· median Rating 1801(2 of 8 problems rated by zerotrac)

Open the Line 500 list · stop 21 · 8 problems
Learn first
Leads to
No later stop builds on it.
How often asked
asked by 8 companies · in 10 reportsTikTok / ByteDance 3, Confluent 1, Glean 1, Meta 1, PayPal 1

Warm up with this one

LC 79Word SearchMedium
Stuck? Peek at the approach

Backtrack through a grid to match a word without reusing a cell within one path.

Key points

  1. Place one queen per row so the search branches only on columns; mark columns, diagonals (r-c) and anti-diagonals (r+c) in three arrays.
  2. Prune as early as possible: test for conflicts before recursing, not after the board is full.
  3. For sudoku and combination-sum style problems, sort first and break as soon as the remaining values cannot work; break saves far more than continue.

Common pitfalls

  • The diagonal index r-c can be negative; offset it by n-1.
  • Forgetting to clear the marks before returning wrongly prunes every later branch.
  • When printing boards, edit a mutable character buffer and convert it once at the end instead of copying the whole board at every step.

Watch it run

Step through the pattern on a small example. Pause, step forwards or back, or drag the slider to any step.

Interactive demo · step by step

N-queens · pruning by column and diagonal

How many ways can 4 queens be placed?

Try your own input
·0,0
·0,1
·0,2
·0,3
·1,0
·1,1
·1,2
·1,3
·2,0
·2,1
·2,2
·2,3
·3,0
·3,1
·3,2
·3,3
CurrentDiscovered / computedAnswer
Queens placed
0 / 4
Columns used
—
↘ diagonals r−c
—
↙ diagonals r+c
—
Solutions
0

Place one queen per row on a 4×4 board. Three sets record the used columns and both diagonals, so each check is O(1).

InvariantSquares on one ↘ diagonal share r − c and on one ↙ diagonal share r + c; a queen fits only if none of its three keys is taken.

Template

Open one language. All four implement the same template, and each one is compiled, run and checked against test data. Then rewrite the warm-up, LC 79, with it.

Python
def total_queens(n: int) -> int:
    """Number of ways to place n non-attacking queens on an n x n board."""
    cols, diag, anti = [False] * n, [False] * (2 * n - 1), [False] * (2 * n - 1)

    def place(r: int) -> int:
        if r == n:
            return 1
        count = 0
        for c in range(n):
            d = r - c + n - 1  # shift r - c into 0..2n-2
            if cols[c] or diag[d] or anti[r + c]:
                continue  # attacked: prune this branch
            cols[c] = diag[d] = anti[r + c] = True
            count += place(r + 1)
            cols[c] = diag[d] = anti[r + c] = False  # undo
        return count

    return place(0)
C++
// Number of ways to place n non-attacking queens on an n x n board.
int totalQueens(int n) {
    vector<bool> cols(n), diag(2 * n - 1), anti(2 * n - 1);
    function<int(int)> place = [&](int r) {
        if (r == n) return 1;
        int count = 0;
        for (int c = 0; c < n; c++) {
            int d = r - c + n - 1;  // shift r - c into 0..2n-2
            if (cols[c] || diag[d] || anti[r + c]) continue;  // attacked: prune this branch
            cols[c] = diag[d] = anti[r + c] = true;
            count += place(r + 1);
            cols[c] = diag[d] = anti[r + c] = false;  // undo
        }
        return count;
    };
    return place(0);
}
Java
class Solution {
    private boolean[] cols, diag, anti;
    private int n;

    // Number of ways to place n non-attacking queens on an n x n board.
    int totalQueens(int n) {
        this.n = n;
        cols = new boolean[n];
        diag = new boolean[2 * n - 1];
        anti = new boolean[2 * n - 1];
        return place(0);
    }

    private int place(int r) {
        if (r == n) return 1;
        int count = 0;
        for (int c = 0; c < n; c++) {
            int d = r - c + n - 1; // shift r - c into 0..2n-2
            if (cols[c] || diag[d] || anti[r + c]) continue; // attacked: prune this branch
            cols[c] = diag[d] = anti[r + c] = true;
            count += place(r + 1);
            cols[c] = diag[d] = anti[r + c] = false; // undo
        }
        return count;
    }
}
Go
// totalQueens returns the number of ways to place n non-attacking queens on an n x n board.
func totalQueens(n int) int {
	cols, diag, anti := make([]bool, n), make([]bool, 2*n-1), make([]bool, 2*n-1)
	var place func(r int) int
	place = func(r int) int {
		if r == n {
			return 1
		}
		count := 0
		for c := 0; c < n; c++ {
			d := r - c + n - 1 // shift r - c into 0..2n-2
			if cols[c] || diag[d] || anti[r+c] {
				continue // attacked: prune this branch
			}
			cols[c], diag[d], anti[r+c] = true, true, true
			count += place(r + 1)
			cols[c], diag[d], anti[r+c] = false, false, false // undo
		}
		return count
	}
	return place(0)
}

Common variants

Problems at this stop also need the 2 shapes below. Open one to see when to switch to it; its code is tested in all four languages too.

Sudoku: one bitmask per row, column and boxExponential in the worst case, fast on typical puzzles · O(81) space

For constraint-filling puzzles (Sudoku and its relatives): keep the digits used in each row, column and box as bitmasks so "can d go here" is a single AND, and backtrack over the empty cells, setting bits on the way down and clearing them on the way back. LC 37 (Sudoku Solver); LC 36 (Valid Sudoku) uses the same masks.

Python
def solve_sudoku(board: list[list[str]]) -> bool:
    """Fill the '.' cells in place so each row, column and 3x3 box holds 1-9 once (LC 37)."""
    rows, cols, boxes = [0] * 9, [0] * 9, [0] * 9  # bit d set: digit d is used there
    empty = []
    for r in range(9):
        for c in range(9):
            if board[r][c] == ".":
                empty.append((r, c))
            else:
                bit = 1 << int(board[r][c])
                rows[r] |= bit
                cols[c] |= bit
                boxes[r // 3 * 3 + c // 3] |= bit

    def fill(k: int) -> bool:
        if k == len(empty):
            return True
        r, c = empty[k]
        b = r // 3 * 3 + c // 3
        for d in range(1, 10):
            bit = 1 << d
            if (rows[r] | cols[c] | boxes[b]) & bit:
                continue  # d is already in this row, column or box
            rows[r] |= bit
            cols[c] |= bit
            boxes[b] |= bit
            board[r][c] = str(d)
            if fill(k + 1):
                return True
            rows[r] ^= bit  # undo
            cols[c] ^= bit
            boxes[b] ^= bit
        board[r][c] = "."
        return False

    return fill(0)
C++
// Fill the '.' cells in place so each row, column and 3x3 box holds 1-9 once (LC 37).
bool solveSudoku(vector<string>& board) {
    int rows[9] = {}, cols[9] = {}, boxes[9] = {};  // bit d set: digit d is used there
    vector<pair<int, int>> empty;
    for (int r = 0; r < 9; r++)
        for (int c = 0; c < 9; c++) {
            if (board[r][c] == '.') {
                empty.push_back({r, c});
                continue;
            }
            int bit = 1 << (board[r][c] - '0');
            rows[r] |= bit;
            cols[c] |= bit;
            boxes[r / 3 * 3 + c / 3] |= bit;
        }
    function<bool(size_t)> fill = [&](size_t k) {
        if (k == empty.size()) return true;
        auto [r, c] = empty[k];
        int b = r / 3 * 3 + c / 3;
        for (int d = 1; d <= 9; d++) {
            int bit = 1 << d;
            if ((rows[r] | cols[c] | boxes[b]) & bit) continue;  // d is already in this row, column or box
            rows[r] |= bit;
            cols[c] |= bit;
            boxes[b] |= bit;
            board[r][c] = char('0' + d);
            if (fill(k + 1)) return true;
            rows[r] ^= bit;  // undo
            cols[c] ^= bit;
            boxes[b] ^= bit;
        }
        board[r][c] = '.';
        return false;
    };
    return fill(0);
}
Java
class Solution {
    private final int[] rows = new int[9], cols = new int[9], boxes = new int[9]; // bit d set: digit d is used there
    private final List<int[]> empty = new ArrayList<>();
    private char[][] board;

    // Fill the '.' cells in place so each row, column and 3x3 box holds 1-9 once (LC 37).
    boolean solveSudoku(char[][] board) {
        this.board = board;
        for (int r = 0; r < 9; r++)
            for (int c = 0; c < 9; c++) {
                if (board[r][c] == '.') {
                    empty.add(new int[] {r, c});
                    continue;
                }
                int bit = 1 << (board[r][c] - '0');
                rows[r] |= bit;
                cols[c] |= bit;
                boxes[r / 3 * 3 + c / 3] |= bit;
            }
        return fill(0);
    }

    private boolean fill(int k) {
        if (k == empty.size()) return true;
        int r = empty.get(k)[0], c = empty.get(k)[1], b = r / 3 * 3 + c / 3;
        for (int d = 1; d <= 9; d++) {
            int bit = 1 << d;
            if (((rows[r] | cols[c] | boxes[b]) & bit) != 0) continue; // d is already in this row, column or box
            rows[r] |= bit;
            cols[c] |= bit;
            boxes[b] |= bit;
            board[r][c] = (char) ('0' + d);
            if (fill(k + 1)) return true;
            rows[r] ^= bit; // undo
            cols[c] ^= bit;
            boxes[b] ^= bit;
        }
        board[r][c] = '.';
        return false;
    }
}
Go
// solveSudoku fills the '.' cells in place so each row, column and 3x3 box holds 1-9 once (LC 37).
func solveSudoku(board [][]byte) bool {
	var rows, cols, boxes [9]int // bit d set: digit d is used there
	var empty [][2]int
	for r := 0; r < 9; r++ {
		for c := 0; c < 9; c++ {
			if board[r][c] == '.' {
				empty = append(empty, [2]int{r, c})
				continue
			}
			bit := 1 << (board[r][c] - '0')
			rows[r] |= bit
			cols[c] |= bit
			boxes[r/3*3+c/3] |= bit
		}
	}
	var fill func(k int) bool
	fill = func(k int) bool {
		if k == len(empty) {
			return true
		}
		r, c := empty[k][0], empty[k][1]
		b := r/3*3 + c/3
		for d := 1; d <= 9; d++ {
			bit := 1 << d
			if (rows[r]|cols[c]|boxes[b])&bit != 0 {
				continue // d is already in this row, column or box
			}
			rows[r] |= bit
			cols[c] |= bit
			boxes[b] |= bit
			board[r][c] = byte('0' + d)
			if fill(k + 1) {
				return true
			}
			rows[r] ^= bit // undo
			cols[c] ^= bit
			boxes[b] ^= bit
		}
		board[r][c] = '.'
		return false
	}
	return fill(0)
}

Why it works

  1. Placing exactly one queen per row loses nothing: in any valid board the n queens are in distinct rows, so there is one per row, and searching row by row only fixes the order of enumeration.
  2. Cells on one diagonal share r − c and cells on one anti-diagonal share r + c, so three boolean arrays check a conflict in O(1).
  3. Pruning is safe because a pruned partial board already has a conflict, and placing more queens keeps that conflict, so it can never become valid.

Say it in 30 seconds

When the interviewer asks you to talk it through: the approach, why it is correct, then the cost. One version in each language to read aloud a few times.

中文
N 皇后我按行回溯,每行放一个,只在列上分支。用三个数组分别标记列、主对角线 r − c 和副对角线 r + c,放之前 O(1) 检查冲突,有冲突就不递归,越早剪越好。之所以安全,是因为已经冲突的部分摆法再怎么往下放都不会变合法。数独、组合总和也一样,先排序,后面不可能满足就直接 break。
English
For N-Queens I backtrack row by row, one queen per row, branching only on the column. Three arrays mark used columns, diagonals r − c and anti-diagonals r + c, so I check a conflict in O(1) before recursing and prune as early as possible. That is safe because a partial board with a conflict can never become valid by adding queens. Sudoku and combination sum work the same way: sort first and break as soon as the rest cannot fit.

Grade yourself

Grade your answer against the one above. Questions you have not mastered come back after 1, 3, 7 and 21 days, listed under My progress → Due for review. Kept on this device; sign in and it moves to your account.

Key points you covered (0 of 3)
How well did you know it?

Quick quiz

3 concept and complexity questions. Answered ones come back for spaced review along with the OA multiple-choice practice. Open the OA multiple-choice practice

3 questions
  1. In N-Queens, queens at (r1, c1) and (r2, c2) share a diagonal exactly when:
  2. In Combination Sum with positive candidates sorted ascending, why may the loop break (not just skip) once candidates[i] exceeds the remaining target?
  3. Searching a grid for a word by backtracking, why mark the current cell as in use before recursing and restore it afterwards?

Your answers stay in this browser on this device; open OA multiple-choice practice signed in to keep them in your account.

Template drills

Drills cut from the templates above: put shuffled lines back in order, fill the blanked boundary conditions back in, or write a whole template from memory in an empty editor, run against this stop's tests and compared line by line. Another one gives a new drill.

These lines are shuffled. Tap a line to pick it, then tap another to swap them, until they read as the template does; the indentation is a hint.

def total_queens(n: int) -> int:
    """Number of ways to place n non-attacking queens on an n x n board."""
    cols, diag, anti = [False] * n, [False] * (2 * n - 1), [False] * (2 * n - 1)

    return place(0)

Practice by stage

This stop's 8 Line 500 problems in three stages: Foundation, Core and Advanced. Each has a one-line approach; try it yourself before reading it.

Core 4

#ProblemApproachRating
79Word SearchBacktrack through a grid to match a word without reusing a cell within one path.
51N-QueensPlace queens row by row and prune conflicts in columns and both diagonal directions.
52N-Queens IICount valid placements instead of storing them to practice constraint search without result storage.
1239Maximum Length of a Concatenated String with Unique CharactersTrack used characters while choosing strings and prune immediately on a conflict.Rating 1720

Advanced 4

#ProblemApproachRating
212Word Search IICombine multiword matching with trie pruning to avoid traversing the grid separately for every word.
37Sudoku SolverMaintain row, column, and box constraints for Sudoku, prioritizing the cell with the fewest candidates.
67924 GameCombine two numbers at a time across possible operations, covering different parenthesizations and handling numeric comparisons.
1255Maximum Score Words Formed by LettersChoose words by backtracking and subtract their letter requirements to maximize score within the available inventory.Rating 1882