N-Queens
LeetCode 51 · Hard · solution, intuition & step-by-step walkthrough
Column-by-column backtracking with row + diagonal hashes.
This is how I solved N-Queens (LeetCode 51), a hard problem from the Constraint Satisfaction pattern. Below: the intuition, the approach step by step, my accepted Python code and the 2 versions I wrote on the way, animated test cases and a line-by-line debugger.
Intuition
Place one queen per column. For each row in the current column, place a queen if no earlier queen attacks that square, recurse to the next column, then remove it. Attacks can be checked by scanning, or in O(1) with arrays for rows and both diagonals.
Approach
- 1
Version 1: check left, upper-left and lower-left squares by scanning.
- 2
Version 2: row_hash[row], diag[row+col], anti-diag[n−1+col−row].
- 3
Place, mark, recurse, unmark.
- 4
col == n → record the board.
How I solved it · from first idea to final
Walk three directions.
O(1) attack check.
Scan for attacksPythonO(n!·n) time
class Solution:
def solveNQueens(self, n: int) -> List[List[str]]:
res=[]
board = [["."]*n for _ in range(n)]
def can_place_queen(row,col,board):
temp_row = row
temp_col = col
#move left
while col>=0:
if board[row][col]=="Q":
return False
col-=1
#left diagonal
row = temp_row
col = temp_col
while row>=0 and col>=0:
if board[row][col]=="Q":
return False
row-=1
col-=1
#bottom diagonal
row = temp_row
col = temp_col
while row<n and col>=0:
if board[row][col]=="Q":
return False
row+=1
col-=1
return True
def backtrack(col,board):
if col==n:
res.append(["".join(row) for row in board])
return
for row in range(n):
if can_place_queen(row,col,board):
board[row][col]="Q"
backtrack(col+1,board)
board[row][col]="."
backtrack(0,board)
return resHash arraysPythonO(n!) time
class Solution:
def solveNQueens(self, n: int) -> List[List[str]]:
res=[]
board = [["."]*n for _ in range(n)]
row_hash = [0]*n
bottom_left_diagonal = [0]*(2*n-1)
top_left_diagonal = [0]*(2*n-1)
def backtrack(col,board):
if col==n:
res.append(["".join(row) for row in board])
return
for row in range(n):
if row_hash[row]==0 and bottom_left_diagonal[row+col]==0 and top_left_diagonal[n-1+col-row]==0:
board[row][col]="Q"
row_hash[row]=1
bottom_left_diagonal[row+col]=1
top_left_diagonal[n-1+col-row]=1
backtrack(col+1,board)
board[row][col]="."
row_hash[row]=0
bottom_left_diagonal[row+col]=0
top_left_diagonal[n-1+col-row]=0
backtrack(0,board)
return resN-Queens — FAQ
What is the intuition behind N-Queens?
Place one queen per column. For each row in the current column, place a queen if no earlier queen attacks that square, recurse to the next column, then remove it. Attacks can be checked by scanning, or in O(1) with arrays for rows and both diagonals.
How do you solve N-Queens (LeetCode 51)?
1. Version 1: check left, upper-left and lower-left squares by scanning. 2. Version 2: row_hash[row], diag[row+col], anti-diag[n−1+col−row]. 3. Place, mark, recurse, unmark. 4. col == n → record the board.
What is the time and space complexity of N-Queens?
Time: O(n!). Space: O(n²) board. (Accepted approach: Hash arrays.)
What are common mistakes in N-Queens?
Only check to the left — columns to the right are still empty.
Is there more than one way to solve N-Queens?
Scan for attacks (O(n!·n) time): Walk three directions. Hash arrays (O(n!) time): O(1) attack check.