Leetcode #51: N-Queens
In this guide, we solve Leetcode #51 N-Queens 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 all distinct solutions to the n-queens puzzle.
Quick Facts
- Difficulty: Hard
- Premium: No
- Tags: Array, 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: [[".Q..","...Q","Q...","..Q."],["..Q.","Q...","...Q",".Q.."]]
Explanation: There exist two distinct solutions to the 4-queens puzzle as shown above
Python Solution
class Solution:
def solveNQueens(self, n: int) -> List[List[str]]:
def dfs(i: int):
if i == n:
ans.append(["".join(row) for row in g])
return
for j in range(n):
if col[j] + dg[i + j] + udg[n - i + j] == 0:
g[i][j] = "Q"
col[j] = dg[i + j] = udg[n - i + j] = 1
dfs(i + 1)
col[j] = dg[i + j] = udg[n - i + j] = 0
g[i][j] = "."
ans = []
g = [["."] * n for _ in range(n)]
col = [0] * n
dg = [0] * (n << 1)
udg = [0] * (n << 1)
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.