Coding interview problems āŗ Backtracking
š§© Backtracking Hard
N-Queens
N-Queens explained: place queens row by row with backtracking and O(1) column and diagonal checks, tested Python returning every board, with a live visual.
Also searched as: N queens problem backtracking Ā· 8 queens problem Ā· place n queens so none attack
Try it live Free
N-Queens & Backtracking
Place queens column by column, watch them get attacked, back up and lock into a safe board; this solution does the same thing row by row.
Also useful: Backtracking: Subsets, Permutations & Pruning
The problem
Place n queens on an n Ć n chessboard so that no two queens attack each other (no two share a row, column or diagonal). Return every distinct solution, each drawn as a list of strings with Q for a queen and . for an empty square.
The key insight
Every row must hold exactly one queen, so place them one row at a time. For each row try each column, but only if that column and both diagonals are free. Cells on the same "\" diagonal share row - col; cells on the same "/" diagonal share row + col. Three sets make each safety check O(1), and a dead end immediately undoes the last queen.
Step-by-step approach
- Keep sets
cols,diag(row - col) andanti(row + col), plusqueens, the column chosen in each row. - Define
dfs(row): ifrow == n, convertqueensinto a board and record it. - For each column
c, skip it ifc,row - corrow + cis already taken. - Otherwise add all three, append
c, recurse onrow + 1, then remove them (backtrack). - Call
dfs(0).
Python solution
def solve_n_queens(n):
out, queens = [], [] # queens[r] = column in row r
cols, diag, anti = set(), set(), set()
def dfs(row):
if row == n:
out.append(["." * c + "Q" + "." * (n - c - 1) for c in queens])
return
for c in range(n):
if c in cols or row - c in diag or row + c in anti:
continue # attacked: prune
cols.add(c); diag.add(row - c); anti.add(row + c)
queens.append(c)
dfs(row + 1)
queens.pop()
cols.remove(c); diag.remove(row - c); anti.remove(row + c)
dfs(0)
return outComplexity
Row r has at most n - r free columns, so the search is bounded by n!, and pruning on diagonals makes it far smaller. The sets and recursion hold O(n) entries (plus O(n²) per stored board).
Common mistakes
- Checking only columns and forgetting one of the two diagonals.
- Using
row + colfor both diagonals; the other one needsrow - col. - Forgetting to remove a queen's entries from all three sets when backtracking.
Frequently asked questions
What is the time and space complexity of N-Queens?
The search is bounded by O(n!) because each row has fewer free columns than the last, and pruning makes it much faster in practice. Extra space is O(n) for the sets and recursion, plus the output boards.
How many solutions does N-Queens have?
For n = 1 to 8: 1, 0, 0, 2, 10, 4, 40, 92. The classic 8-queens puzzle has 92 solutions.
How do I just count the solutions (N-Queens II)?
Use the same backtracking and increment a counter at row == n instead of building boards. Bitmasks for columns and diagonals make it even faster.
Why do cells on a diagonal share row - col?
Moving one step down-right adds 1 to both row and column, so their difference stays constant. Moving down-left adds 1 to row and subtracts 1 from column, so their sum stays constant.
Preparing for placements?
Take the 2-minute readiness check to find your weak patterns, then follow the placement path from DSA core to system design.
All coding interview problems More Backtracking Backtracking: Subsets, Permutations & Pruning lab Placement prep guides
Problem statements on this site are written in our own words. Problem names are the common names used across interview-prep communities; BitBootcamp is an independent learning platform and is not affiliated with LeetCode or any company that asks these questions.