N-Queens II (LeetCode 52): Solution and Explanation
Count how many ways you can place n queens on an n x n board so that no two of them share a row, a column or a diagonal. Unlike N-Queens, you only return the number of arrangements, not the boards themselves.
Intuition
A queen controls its whole row, so a valid board has exactly one queen per row. That turns the problem into a sequence of choices: pick a column for row 0, then for row 1, and so on. Backtracking explores those choices depth first and undoes each one after exploring it.
The question at every step is whether a square is safe. Scanning the board for that is slow, but every attack line has a simple label. All squares in one column share c. All squares on one down-right diagonal share r - c. All squares on one down-left diagonal share r + c. Keep a set for each label and a square is safe exactly when its three labels are all free.
Because the answer is only a count, you do not need to build or copy boards. The recursion returns how many completions exist below the current partial board, and reaching row n counts as one.
Approach: Backtracking with column and diagonal sets
- Create three empty sets:
cols,diag(storesr - c) andanti(storesr + c). - Define
place(r). Ifr == n, every row has a queen, so return 1. - Otherwise loop over columns
c. Skip any column wherec,r - corr + cis already taken. - For a safe column, add the three labels, add
place(r + 1)to a running count, then remove the labels. - Return the running count, and call
place(0)for the answer.
Step-by-step example
n = 4
- Row 0, column 0 is safe. Mark col 0, r-c = 0, r+c = 0.
- Row 1: columns 0 and 1 are attacked; column 2 is safe. Row 2 then has no safe column, so lift the row 1 queen and try column 3.
- With queens at (0,0) and (1,3), row 2 can use column 1, but row 3 has no safe square. Backtrack all the way and lift the row 0 queen.
- Row 0, column 1: the chain (0,1), (1,3), (2,0), (3,2) completes. Count = 1.
- Row 0, column 2 mirrors that: (0,2), (1,0), (2,3), (3,1) completes. Count = 2.
- Row 0, column 3 leads nowhere, so the answer is 2.
Code: Python, Java, C++
1class Solution:
2 def totalNQueens(self, n: int) -> int:
3 cols, diag, anti = set(), set(), set()
4
5 def place(r: int) -> int:
6 if r == n:
7 return 1
8 count = 0
9 for c in range(n):
10 if c in cols or r - c in diag or r + c in anti:
11 continue
12 cols.add(c); diag.add(r - c); anti.add(r + c)
13 count += place(r + 1)
14 cols.remove(c); diag.remove(r - c); anti.remove(r + c)
15 return count
16
17 return place(0)1class Solution {
2 private boolean[] cols, diag, anti;
3 private int n;
4
5 public int totalNQueens(int n) {
6 this.n = n;
7 cols = new boolean[n];
8 diag = new boolean[2 * n];
9 anti = new boolean[2 * n];
10 return place(0);
11 }
12
13 private int place(int r) {
14 if (r == n) return 1;
15 int count = 0;
16 for (int c = 0; c < n; c++) {
17 if (cols[c] || diag[r - c + n] || anti[r + c]) continue;
18 cols[c] = diag[r - c + n] = anti[r + c] = true;
19 count += place(r + 1);
20 cols[c] = diag[r - c + n] = anti[r + c] = false;
21 }
22 return count;
23 }
24}1class Solution {
2public:
3 int totalNQueens(int n) {
4 this->n = n;
5 cols.assign(n, false);
6 diag.assign(2 * n, false);
7 anti.assign(2 * n, false);
8 return place(0);
9 }
10
11private:
12 int n;
13 vector<bool> cols, diag, anti;
14
15 int place(int r) {
16 if (r == n) return 1;
17 int count = 0;
18 for (int c = 0; c < n; c++) {
19 if (cols[c] || diag[r - c + n] || anti[r + c]) continue;
20 cols[c] = diag[r - c + n] = anti[r + c] = true;
21 count += place(r + 1);
22 cols[c] = diag[r - c + n] = anti[r + c] = false;
23 }
24 return count;
25 }
26};Time and space complexity
O(n!)
Row 0 has at most n choices, row 1 at most n - 1 that avoid the first column, and so on, so the search tree has at most n! leaves. Diagonal pruning cuts it down much further, and each safety check is O(1).
O(n)
The three sets hold at most n labels each, and the recursion is n levels deep.
Other approaches
Scan the board for conflicts (time O(n! * n), space O(n^2))
Keep an actual board and, before placing, walk up the column and both diagonals to look for a queen. It is the classic textbook version and easy to follow, but each check costs O(n).
Bitmask backtracking (time O(n!), space O(n))
Store columns and diagonals as three integers and compute the free squares of a row with ~(cols | diag | anti) & ((1 << n) - 1). Taking the lowest set bit picks the next column. It is the fastest version in practice and a common follow-up.
Lookup table (time O(1), space O(1))
Since n is at most 9, the answers 1, 0, 0, 2, 10, 4, 40, 92, 352 can be hard-coded. It passes, but it shows nothing about the algorithm, so it is not a good interview answer.
Common mistakes
- Forgetting to remove the column and diagonal labels after the recursive call, which leaves stale attacks and undercounts.
- Using
r - cas an array index without an offset. It can be negative, so shift it by n (or use a set). - Mixing up the diagonals. Squares on the same down-right diagonal share
r - c; squares on the same down-left diagonal sharer + c. - Building and copying full boards just to count them, which wastes time and memory.
Frequently asked questions
How is N-Queens II different from N-Queens?
N-Queens asks for every board as a list of strings. N-Queens II only asks for how many there are, so you can skip building boards and return counts from the recursion.
Why is r - c constant along a diagonal?
Moving one step down-right adds 1 to both r and c, so their difference does not change. Moving down-left adds 1 to r and subtracts 1 from c, so r + c stays the same.
Why are there no solutions for n = 2 and n = 3?
On boards that small, any queen in the first row attacks every square of the second row, or leaves the third row with no safe square. The search simply finds no complete board and returns 0.
What is the time complexity?
The search is bounded by O(n!) because each row uses a column no earlier row used, and every safety check is O(1) with the three sets.