N-Queens
Difficulty: Hard
Place n queens on an n x n chessboard so that no two attack each other - no two share a row, column or diagonal.
Return every distinct placement. Each solution is one full board, with each row written using "Q" for a queen and "." for an empty square.
Examples
Input: n = 4
Output: [[".Q..","...Q","Q...","..Q."], ["..Q.","Q...","...Q",".Q.."]]
There are exactly two ways to place 4 non-attacking queens on a 4x4 board. In the first, the queens sit at row 0 col 1, row 1 col 3, row 2 col 0, and row 3 col 2.
Input: n = 1
Output: [["Q"]]
A single queen on a 1x1 board never conflicts with anything.
Constraints
1 <= n <= 9
Approach
No two queens can share a row, so place them one row at a time: choose a column for row 0, then a non-conflicting column for row 1, and so on. When every row has a queen with no conflicts, you have one solution.
The simple conflict check compares the candidate with every queen in earlier rows (columns and diagonals). It's easy to write, but re-scans all earlier queens on every attempt.
A faster way keeps three trackers: used columns and the two used diagonal directions. One diagonal is identified by row minus column, the other by row plus column - two cells on the same diagonal share one of these values. Checking a column is then a lookup instead of a scan, and removing a queen just removes its column and diagonals from the trackers.
Solutions
Backtracking — Scan Previously Placed Queens
Place queens row by row. For each row, try every column, checking that no queen in an earlier row shares the column or either diagonal. If it's safe, place the queen, recurse into the next row, then remove it and try the next column.
function solveNQueens(n) {
const result = [];
const queenCol = new Array(n).fill(-1); // queenCol[row] = column of the queen in that row
function isSafe(row, col) {
for (let prevRow = 0; prevRow < row; prevRow++) {
const prevCol = queenCol[prevRow];
const sameCol = prevCol === col;
const sameDiagonal = Math.abs(prevRow - row) === Math.abs(prevCol - col);
if (sameCol || sameDiagonal) return false;
}
return true;
}
function buildBoard() {
return queenCol.map((col) => ".".repeat(col) + "Q" + ".".repeat(n - col - 1));
}
function backtrack(row) {
if (row === n) {
result.push(buildBoard());
return;
}
for (let col = 0; col < n; col++) {
if (isSafe(row, col)) {
queenCol[row] = col;
backtrack(row + 1);
queenCol[row] = -1; // undo
}
}
}
backtrack(0);
return result;
}Time: O(n! * n) - roughly n! branching once pruning kicks in, times O(n) per safety scan · Space: O(n) for the queenCol array and recursion depth (output is separate)
Optimal — Track Columns and Diagonals with Sets
Instead of re-scanning earlier queens, keep three sets: used columns, used "row minus column" diagonals, and used "row plus column" diagonals. Placing or removing a queen adds or deletes one entry in each set, and checking a column is three constant-time lookups.
function solveNQueens(n) {
const result = [];
const queenCol = new Array(n).fill(-1);
const usedCols = new Set();
const usedDiag1 = new Set(); // row - col
const usedDiag2 = new Set(); // row + col
function buildBoard() {
return queenCol.map((col) => ".".repeat(col) + "Q" + ".".repeat(n - col - 1));
}
function backtrack(row) {
if (row === n) {
result.push(buildBoard());
return;
}
for (let col = 0; col < n; col++) {
const d1 = row - col;
const d2 = row + col;
if (usedCols.has(col) || usedDiag1.has(d1) || usedDiag2.has(d2)) continue;
queenCol[row] = col;
usedCols.add(col);
usedDiag1.add(d1);
usedDiag2.add(d2);
backtrack(row + 1);
usedCols.delete(col);
usedDiag1.delete(d1);
usedDiag2.delete(d2);
}
}
backtrack(0);
return result;
}Time: O(n!) - each placement check is now O(1) instead of O(n) · Space: O(n) for the tracking sets and recursion depth (output is separate)