51. N-Queens
Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.
Approach
1. Problem Analysis
The N-Queens puzzle requires placing N queens on an N x N chessboard such that no two queens threaten each other. This means no two queens can share the same row, column, or diagonal. The task is to find all possible distinct configurations for a given N. This is a classic combinatorial problem that can be solved by exploring all possible placements of queens and eliminating invalid ones.
Solution
N-Queens in Python
class Solution:
def solveNQueens(self, n: int) -> List[List[str]]:
results = []
# `queens` stores the column index for the queen in each row.
queens = [-1] * n
# Sets to keep track of occupied columns and diagonals.
cols = set()
diag1 = set() # For diagonals where r + c is constant
diag2 = set() # For diagonals where r - c is constant
def backtrack(row):
# Base case: If all queens are placed successfully.
if row == n:
# Construct the board from the `queens` array and add to results.
board = []
for r in range(n):
line = ['.'] * n
line[queens[r]] = 'Q'
board.append("".join(line))
results.append(board)
return
# Try placing a queen in each column of the current row.
for col in range(n):
# Check if this position is under attack.
if col in cols or (row + col) in diag1 or (row - col) in diag2:
continue
# Place the queen.
queens[row] = col
cols.add(col)
diag1.add(row + col)
diag2.add(row - col)
# Recur for the next row.
backtrack(row + 1)
# Backtrack: remove the queen and reset the state.
cols.remove(col)
diag1.remove(row + col)
diag2.remove(row - col)
backtrack(0)
return results
N-Queens in Java
class Solution {
private List<List<String>> results;
private int[] queens; // queens[i] = column of queen in row i
private boolean[] cols;
private boolean[] diag1; // For diagonals where r + c is constant
private boolean[] diag2; // For diagonals where r - c is constant
private int n;
public List<List<String>> solveNQueens(int n) {
this.n = n;
results = new ArrayList<>();
queens = new int[n];
cols = new boolean[n];
diag1 = new boolean[2 * n - 1];
diag2 = new boolean[2 * n - 1];
backtrack(0);
return results;
}
private void backtrack(int row) {
// Base case: If all queens are placed successfully.
if (row == n) {
// Construct the board and add it to the results.
List<String> board = new ArrayList<>();
for (int i = 0; i < n; i++) {
char[] rowChars = new char[n];
Arrays.fill(rowChars, '.');
rowChars[queens[i]] = 'Q';
board.add(new String(rowChars));
}
results.add(board);
return;
}
// Try placing a queen in each column of the current row.
for (int col = 0; col < n; col++) {
// Check if this position is under attack.
// diag1 index: row + col
// diag2 index: row - col + (n - 1) to handle negative values.
if (cols[col] || diag1[row + col] || diag2[row - col + n - 1]) {
continue;
}
// Place the queen.
queens[row] = col;
cols[col] = true;
diag1[row + col] = true;
diag2[row - col + n - 1] = true;
// Recur for the next row.
backtrack(row + 1);
// Backtrack: remove the queen and reset the state.
cols[col] = false;
diag1[row + col] = false;
diag2[row - col + n - 1] = false;
}
}
}
N-Queens in C++
class Solution {
public:
vector<vector<string>> solveNQueens(int n) {
this->n = n;
// `queens` stores the column index for the queen in each row.
queens.resize(n);
// `cols`, `diag1`, `diag2` are used to track occupied columns and diagonals.
cols.resize(n, false);
diag1.resize(2 * n - 1, false);
diag2.resize(2 * n - 1, false);
backtrack(0);
return results;
}
private:
vector<vector<string>> results;
vector<int> queens;
vector<bool> cols;
vector<bool> diag1; // For diagonals where r + c is constant
vector<bool> diag2; // For diagonals where r - c is constant
int n;
void backtrack(int row) {
// Base case: If all queens are placed successfully.
if (row == n) {
// Construct the board from the `queens` array and add to results.
vector<string> board(n, string(n, '.'));
for (int i = 0; i < n; ++i) {
board[i][queens[i]] = 'Q';
}
results.push_back(board);
return;
}
// Try placing a queen in each column of the current row.
for (int col = 0; col < n; ++col) {
// Check if this position is under attack.
// diag1 index: row + col
// diag2 index: row - col + (n - 1) to handle negative values.
if (cols[col] || diag1[row + col] || diag2[row - col + n - 1]) {
continue;
}
// Place the queen.
queens[row] = col;
cols[col] = true;
diag1[row + col] = true;
diag2[row - col + n - 1] = true;
// Recur for the next row.
backtrack(row + 1);
// Backtrack: remove the queen and reset the state.
cols[col] = false;
diag1[row + col] = false;
diag2[row - col + n - 1] = false;
}
}
};
N-Queens in TypeScript
function solveNQueens(n: number): string[][] {
const results: string[][] = [];
// `queens` stores the column index for the queen in each row.
const queens: number[] = new Array(n).fill(-1);
// Boolean arrays to track occupied columns and diagonals.
const cols: boolean[] = new Array(n).fill(false);
const diag1: boolean[] = new Array(2 * n - 1).fill(false); // r + c
const diag2: boolean[] = new Array(2 * n - 1).fill(false); // r - c + n - 1
function backtrack(row: number): void {
// Base case: If all queens are placed successfully.
if (row === n) {
// Construct the board and add it to the results.
const board: string[] = [];
for (let i = 0; i < n; i++) {
const rowStrArr: string[] = new Array(n).fill('.');
rowStrArr[queens[i]] = 'Q';
board.push(rowStrArr.join(''));
}
results.push(board);
return;
}
// Try placing a queen in each column of the current row.
for (let col = 0; col < n; col++) {
// Check if this position is under attack.
// diag1 index: row + col
// diag2 index: row - col + (n - 1) to handle negative values.
if (cols[col] || diag1[row + col] || diag2[row - col + n - 1]) {
continue;
}
// Place the queen.
queens[row] = col;
cols[col] = true;
diag1[row + col] = true;
diag2[row - col + n - 1] = true;
// Recur for the next row.
backtrack(row + 1);
// Backtrack: remove the queen and reset the state.
cols[col] = false;
diag1[row + col] = false;
diag2[row - col + n - 1] = false;
}
}
backtrack(0);
return results;
};
More Hard LeetCode answers
Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.
LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.