#51 N-Queens
frequently reported atByteDance / TikTokAmazonMicrosoftGoogleMeta
the problem
In plain words
Place n queens on an n × n chessboard so that no two attack each other (same row, column or diagonal). Return every distinct board, each as a list of strings with 'Q' and '.'.
in n = 4
out [[".Q..","...Q","Q...","..Q."],["..Q.","Q...","...Q",".Q.."]]
in n = 1
out [["Q"]]
- 1 ≤ n ≤ 9
your turn
Try it before you peek
Read the examples, say the brute force out loud, then write code: here or on LeetCode ↗. Stuck for 20 minutes? Open one hint at a time.
Solve it in the browser
LeetCode-style: complete the class. Compiled by the real javac (Java 17) and judged right here — nothing is sent anywhere.
Solutions are hidden so you can try first. Even 20 minutes of real effort makes the answer stick far better than reading it.
Marking the problem solved, or opening every hint, also shows it.
the aha
Key insight
patternBacktracking with constraint pruning
Exactly one queen per row, so decide one column per row. Squares on the same ↘ diagonal share row − col; on the same ↙ diagonal they share row + col.
solutions
From brute force to optimal
For each row try every column; check the column and both diagonals above by walking the board.
- row == n → record the board.
- For each col: if safe (O(n) scan upwards), place 'Q', recurse(row + 1), remove.
At most n! placements are explored, and each safety test scans up to n rows.
The board; recursion depth is n.
class Solution { public List<List<String>> solveNQueens(int n) { char[][] board = new char[n][n]; for (char[] row : board) Arrays.fill(row, '.'); List<List<String>> result = new ArrayList<>(); place(board, 0, result); return result; } private void place(char[][] board, int row, List<List<String>> result) { int n = board.length; if (row == n) { List<String> snapshot = new ArrayList<>(); for (char[] r : board) snapshot.add(new String(r)); result.add(snapshot); return; } for (int col = 0; col < n; col++) { if (!safe(board, row, col)) continue; board[row][col] = 'Q'; place(board, row + 1, result); board[row][col] = '.'; } } /** Only rows above can hold queens: check up, up-left and up-right. O(n). */ private boolean safe(char[][] board, int row, int col) { for (int r = row - 1, d = 1; r >= 0; r--, d++) { if (board[r][col] == 'Q') return false; if (col - d >= 0 && board[r][col - d] == 'Q') return false; if (col + d < board.length && board[r][col + d] == 'Q') return false; } return true; }}Keep cols[c], diag[row − col + n − 1] and anti[row + col] as booleans; a square is safe iff all three are false.
- row == n → record.
- For each col: skip if any of the three is true.
- Place: set all three true; recurse; remove: set them false.
Row r has at most n − r safe columns, so ≤ n! placements, each O(1) (plus O(n²) per recorded board).
The board for output; the three arrays are O(n) and recursion depth is n.
class Solution { private boolean[] cols, diag, anti; // diag: row - col + n - 1, anti: row + col private char[][] board; private List<List<String>> result; public List<List<String>> solveNQueens(int n) { cols = new boolean[n]; diag = new boolean[2 * n - 1]; anti = new boolean[2 * n - 1]; board = new char[n][n]; for (char[] row : board) Arrays.fill(row, '.'); result = new ArrayList<>(); place(0, n); return result; } private void place(int row, int n) { if (row == n) { // every row has a queen List<String> snapshot = new ArrayList<>(); for (char[] r : board) snapshot.add(new String(r)); result.add(snapshot); return; } for (int col = 0; col < n; col++) { if (cols[col] || diag[row - col + n - 1] || anti[row + col]) continue; // O(1) attack test board[row][col] = 'Q'; cols[col] = diag[row - col + n - 1] = anti[row + col] = true; place(row + 1, n); board[row][col] = '.'; cols[col] = diag[row - col + n - 1] = anti[row + col] = false; } }}Dry run
in the room
How to say it in the interview
talk track
- "One queen per row removes the row constraint entirely; I only choose columns."
- Derive the diagonal ids on a 3×3 sketch: row − col is constant on ↘, row + col on ↙. Offset row − col by n − 1 so it's a valid index.
- Mention the answer counts (n = 4 → 2, n = 8 → 92) as sanity checks.
traps
- Using
row - colas an index without the+ n - 1offset (negative index). - Forgetting to clear the three flags when removing a queen.
what they ask next
Follow-ups
N-Queens II (LC 52) — just the count?
Same search, return a counter instead of boards. Bitmasks for the three sets make it very fast — it's the next problem.
Sudoku Solver (LC 37)?
Same pattern: pick an empty cell, try digits 1–9 that aren't in its row/column/box tables, recurse, undo. Return true at the first full board — see the last problem.
before you submit
Edge cases to test
- n = 1 → [["Q"]].
- n = 2 and n = 3 have no solution → [].
- n = 9 → 352 boards, the maximum.
practise next
Similar problems
- #52N-Queens IIHardin Backtracking
- #37Sudoku SolverHardin Backtracking
- #36Valid SudokuMediumin Hashing