52. N-Queens II
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
The N-Queens II problem is a variation of the classic N-Queens puzzle. The objective is to place n queens on an n x n chessboard in such a way that no two queens threaten each other. A queen can attack any piece in the same row, column, or any of the two diagonals. Instead of returning the board configurations, this problem asks for the total number of distinct solutions.
Solution
N-Queens II in Python
class Solution:
def totalNQueens(self, n: int) -> int:
# State tracking arrays
cols = [False] * n # Tracks occupied columns
# Tracks occupied main diagonals (r - c)
diag1 = [False] * (2 * n - 1)
# Tracks occupied anti-diagonals (r + c)
diag2 = [False] * (2 * n - 1)
# We use a list to hold the count so it can be modified
# by the nested function (like a reference in other languages).
# Alternatively, `nonlocal` keyword could be used.
count = [0]
def backtrack(row: int):
# Base case: A solution is found if we have placed queens in all n rows
if row == n:
count[0] += 1
return
# Iterate through each column in the current row
for col in range(n):
# Calculate indices for the diagonal arrays
# For main diagonal (r - c), we add n - 1 to make the index non-negative
d1_idx = row - col + n - 1
# For anti-diagonal (r + c), the index is already non-negative
d2_idx = row + col
# Check if placing a queen at (row, col) is valid
if not cols[col] and not diag1[d1_idx] and not diag2[d2_idx]:
# Place the queen: mark the column and diagonals as occupied
cols[col] = True
diag1[d1_idx] = True
diag2[d2_idx] = True
# Recurse to the next row
backtrack(row + 1)
# Backtrack: un-place the queen to explore other possibilities
cols[col] = False
diag1[d1_idx] = False
diag2[d2_idx] = False
# Start the backtracking process from the first row (row 0)
backtrack(0)
return count[0]
N-Queens II in Java
class Solution {
private int count;
private int n;
private boolean[] cols; // To check for queens in the same column
private boolean[] diag1; // To check for queens on the main diagonal (r - c)
private boolean[] diag2; // To check for queens on the anti-diagonal (r + c)
public int totalNQueens(int n) {
this.n = n;
this.count = 0;
this.cols = new boolean[n];
this.diag1 = new boolean[2 * n - 1];
this.diag2 = new boolean[2 * n - 1];
backtrack(0);
return count;
}
private void backtrack(int row) {
// Base case: If we have successfully placed queens in all rows from 0 to n-1
if (row == n) {
count++;
return;
}
// Iterate through each column in the current row
for (int col = 0; col < n; col++) {
// Calculate indices for the diagonal arrays
// For main diagonal (r - c), add n-1 to make index non-negative
int d1_idx = row - col + n - 1;
// For anti-diagonal (r + c), index is directly usable
int d2_idx = row + col;
// Check if placing a queen at (row, col) is valid
if (!cols[col] && !diag1[d1_idx] && !diag2[d2_idx]) {
// Place the queen: mark the column and diagonals as occupied
cols[col] = true;
diag1[d1_idx] = true;
diag2[d2_idx] = true;
// Recurse to the next row
backtrack(row + 1);
// Backtrack: un-place the queen to explore other possibilities
cols[col] = false;
diag1[d1_idx] = false;
diag2[d2_idx] = false;
}
}
}
}
N-Queens II in C++
class Solution {
public:
int totalNQueens(int n) {
// Member variables to store state, could also be passed as parameters.
// Using members simplifies the recursive function signature.
this->n = n;
cols.resize(n, false);
diag1.resize(2 * n - 1, false);
diag2.resize(2 * n - 1, false);
count = 0;
backtrack(0);
return count;
}
private:
int n;
int count;
std::vector<bool> cols; // To check for queens in the same column
std::vector<bool> diag1; // To check for queens on the main diagonal (r - c)
std::vector<bool> diag2; // To check for queens on the anti-diagonal (r + c)
void backtrack(int row) {
// Base case: If we have successfully placed queens in all rows from 0 to n-1
if (row == n) {
count++;
return;
}
// Iterate through each column in the current row
for (int col = 0; col < n; ++col) {
// Calculate indices for the diagonal arrays
// For main diagonal (r - c), add n-1 to make index non-negative
int d1_idx = row - col + n - 1;
// For anti-diagonal (r + c), index is directly usable
int d2_idx = row + col;
// Check if placing a queen at (row, col) is valid
if (!cols[col] && !diag1[d1_idx] && !diag2[d2_idx]) {
// Place the queen: mark the column and diagonals as occupied
cols[col] = true;
diag1[d1_idx] = true;
diag2[d2_idx] = true;
// Recurse to the next row
backtrack(row + 1);
// Backtrack: un-place the queen to explore other possibilities
cols[col] = false;
diag1[d1_idx] = false;
diag2[d2_idx] = false;
}
}
}
};
N-Queens II in TypeScript
function totalNQueens(n: number): number {
let count = 0;
// State tracking arrays
const cols = new Array(n).fill(false); // Tracks occupied columns
// Tracks occupied main diagonals (r - c)
const diag1 = new Array(2 * n - 1).fill(false);
// Tracks occupied anti-diagonals (r + c)
const diag2 = new Array(2 * n - 1).fill(false);
function backtrack(row: number): void {
// Base case: A solution is found if we have placed queens in all n rows
if (row === n) {
count++;
return;
}
// Iterate through each column in the current row
for (let col = 0; col < n; col++) {
// Calculate indices for the diagonal arrays
// For main diagonal (r - c), we add n - 1 to make the index non-negative
const d1_idx = row - col + n - 1;
// For anti-diagonal (r + c), the index is already non-negative
const d2_idx = row + col;
// Check if placing a queen at (row, col) is valid
if (!cols[col] && !diag1[d1_idx] && !diag2[d2_idx]) {
// Place the queen: mark the column and diagonals as occupied
cols[col] = true;
diag1[d1_idx] = true;
diag2[d2_idx] = true;
// Recurse to the next row
backtrack(row + 1);
// Backtrack: un-place the queen to explore other possibilities
cols[col] = false;
diag1[d1_idx] = false;
diag2[d2_idx] = false;
}
}
}
// Start the backtracking process from the first row (row 0)
backtrack(0);
return count;
};
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.