STOP 21 · BACKTRACKING
Constraint Search and Pruning
N-Queens: prune by column and both diagonals O(n!) worst case
- 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 SearchStuck? Peek at the approach
Backtrack through a grid to match a word without reusing a cell within one path.
Key points
- 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.
- Prune as early as possible: test for conflicts before recursing, not after the board is full.
- 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.
N-queens · pruning by column and diagonal
How many ways can 4 queens be placed?
Try your own input
- 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.
Grid backtracking: mark in place, restore on returnO(rows × cols × 3^L) time · O(L) recursion depth
To spell a word along a path of grid cells, each used at most once: DFS from every cell, overwrite the current cell with a marker meaning "used on this path", and restore it after trying all four directions, with no separate visited array. LC 79 (Word Search); LC 212 (Word Search II) searches a whole trie of words at once.
Python
def exist(board: list[list[str]], word: str) -> bool:
"""Is word spelled by a path of side-adjacent cells, each used at most once? (LC 79)"""
rows, cols = len(board), len(board[0])
def dfs(r: int, c: int, k: int) -> bool: # does board[r][c] start word[k:]?
if board[r][c] != word[k]:
return False
if k == len(word) - 1:
return True
board[r][c] = "#" # used on this path
found = any(
0 <= nr < rows and 0 <= nc < cols and dfs(nr, nc, k + 1)
for nr, nc in ((r + 1, c), (r - 1, c), (r, c + 1), (r, c - 1))
)
board[r][c] = word[k] # restore on the way back
return found
return any(dfs(r, c, 0) for r in range(rows) for c in range(cols))C++
// Is word spelled by a path of side-adjacent cells, each used at most once? (LC 79)
bool exist(vector<string> board, const string& word) {
int rows = board.size(), cols = board[0].size();
function<bool(int, int, int)> dfs = [&](int r, int c, int k) { // does board[r][c] start word[k..]?
if (r < 0 || r >= rows || c < 0 || c >= cols || board[r][c] != word[k]) return false;
if (k == (int)word.size() - 1) return true;
board[r][c] = '#'; // used on this path
bool found = dfs(r + 1, c, k + 1) || dfs(r - 1, c, k + 1) || dfs(r, c + 1, k + 1) || dfs(r, c - 1, k + 1);
board[r][c] = word[k]; // restore on the way back
return found;
};
for (int r = 0; r < rows; r++)
for (int c = 0; c < cols; c++)
if (dfs(r, c, 0)) return true;
return false;
}Java
class Solution {
private char[][] board;
private String word;
// Is word spelled by a path of side-adjacent cells, each used at most once? (LC 79)
boolean exist(char[][] board, String word) {
this.board = board;
this.word = word;
for (int r = 0; r < board.length; r++)
for (int c = 0; c < board[0].length; c++)
if (dfs(r, c, 0)) return true;
return false;
}
// Does board[r][c] start word[k..]?
private boolean dfs(int r, int c, int k) {
if (r < 0 || r >= board.length || c < 0 || c >= board[0].length || board[r][c] != word.charAt(k)) return false;
if (k == word.length() - 1) return true;
board[r][c] = '#'; // used on this path
boolean found = dfs(r + 1, c, k + 1) || dfs(r - 1, c, k + 1) || dfs(r, c + 1, k + 1) || dfs(r, c - 1, k + 1);
board[r][c] = word.charAt(k); // restore on the way back
return found;
}
}Go
// exist reports whether word is spelled by a path of side-adjacent cells, each used at most once (LC 79).
func exist(board [][]byte, word string) bool {
rows, cols := len(board), len(board[0])
var dfs func(r, c, k int) bool // does board[r][c] start word[k:]?
dfs = func(r, c, k int) bool {
if r < 0 || r >= rows || c < 0 || c >= cols || board[r][c] != word[k] {
return false
}
if k == len(word)-1 {
return true
}
board[r][c] = '#' // used on this path
found := dfs(r+1, c, k+1) || dfs(r-1, c, k+1) || dfs(r, c+1, k+1) || dfs(r, c-1, k+1)
board[r][c] = word[k] // restore on the way back
return found
}
for r := 0; r < rows; r++ {
for c := 0; c < cols; c++ {
if dfs(r, c, 0) {
return true
}
}
}
return false
}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
- 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.
- 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).
- 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。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.
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
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
| # | Problem | Approach | Rating |
|---|---|---|---|
| 79 | Word Search | Backtrack through a grid to match a word without reusing a cell within one path. | |
| 51 | N-Queens | Place queens row by row and prune conflicts in columns and both diagonal directions. | |
| 52 | N-Queens II | Count valid placements instead of storing them to practice constraint search without result storage. | |
| 1239 | Maximum Length of a Concatenated String with Unique Characters | Track used characters while choosing strings and prune immediately on a conflict. |
Advanced 4
| # | Problem | Approach | Rating |
|---|---|---|---|
| 212 | Word Search II | Combine multiword matching with trie pruning to avoid traversing the grid separately for every word. | |
| 37 | Sudoku Solver | Maintain row, column, and box constraints for Sudoku, prioritizing the cell with the fewest candidates. | |
| 679 | 24 Game | Combine two numbers at a time across possible operations, covering different parenthesizations and handling numeric comparisons. | |
| 1255 | Maximum Score Words Formed by Letters | Choose words by backtracking and subtract their letter requirements to maximize score within the available inventory. |