Leetcode #52: N-Queens II
In this guide, we solve Leetcode #52 N-Queens II in Python and focus on the core idea that makes the solution efficient.
You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Problem Statement
The n-queens puzzle is the problem of placing n queens on an n x n chessboard such that no two queens attack each other. Given an integer n, return the number of distinct solutions to the n-queens puzzle.
Quick Facts
- Difficulty: Hard
- Premium: No
- Tags: Backtracking
Intuition
We must explore combinations of choices, but many branches can be pruned early.
Backtracking enumerates valid candidates while keeping the search space under control.
Approach
Use DFS to build candidates step by step, and backtrack when constraints are violated.
Pruning keeps the exploration practical for typical constraints.
Steps:
- Define the decision tree.
- DFS through choices and backtrack.
- Prune invalid paths early.
Example
Input: n = 4
Output: 2
Explanation: There are two distinct solutions to the 4-queens puzzle as shown.
Python Solution
class Solution:
def totalNQueens(self, n: int) -> int:
def dfs(i: int):
if i == n:
nonlocal ans
ans += 1
return
for j in range(n):
a, b = i + j, i - j + n
if cols[j] or dg[a] or udg[b]:
continue
cols[j] = dg[a] = udg[b] = True
dfs(i + 1)
cols[j] = dg[a] = udg[b] = False
cols = [False] * 10
dg = [False] * 20
udg = [False] * 20
ans = 0
dfs(0)
return ans
Complexity
The time complexity is , and the space complexity is . The space complexity is .
Edge Cases and Pitfalls
Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.
Summary
This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.