#51
Hard
Backtracking

N-Queens

Place n queens on an n x n board so that none attack each other.

Backtracking

Pattern fit

This is a classic constraint backtracking problem where pruning matters more than raw recursion, because invalid board states should be rejected immediately.

Key observation

At each row you only need to know which columns and diagonals are already occupied.

Target complexity

Exponential / O(n)

How to break down the solution cleanly

1

This is a classic constraint backtracking problem where pruning matters more than raw recursion, because invalid board states should be rejected immediately.

2

At each row you only need to know which columns and diagonals are already occupied.

3

Model the decision tree explicitly.

4

Choose the next candidate set for the current depth.

Reference implementation

Python
# Generic pattern template
def backtrack(path):
    if complete(path):
        answer.append(path[:])
        return
    for choice in choices(path):
        if not valid(choice, path):
            continue
        path.append(choice)
        backtrack(path)
        path.pop()

Common pitfalls

warning

Checking the whole board for every candidate instead of maintaining sets.

warning

Forgetting diagonal indexing rules.

Common follow-ups

How do diagonal sets map to row and column?

Could bitmasks speed this up?

Continue with related problems

Build repeatable depth inside the Backtracking cluster before moving on.

view_weekBack to the pattern page
LeetCode 51. N-Queens Guide | Interview AiBox