InterviewPrepKit

Home / Coding / Algorithm & Data Structure / Backtracking

N-Queens

hard Original ↗ 00:00

Problem

Place n chess queens on an n x n board so that no two queens attack each other — no two share a row, a column, or a diagonal. Return all distinct valid placements. Each placement is rendered as a list of n strings of length n, where 'Q' marks a queen and '.' an empty square. Solutions may be returned in any order.

Examples

  • n = 4 → two solutions:
. Q . .      . . Q .
. . . Q      Q . . .
Q . . .      . . . Q
. . Q .      . Q . .

Each is the other’s mirror image; no smaller-than-4 board other than n=1 admits any solution.

  • n = 1[["Q"]] — a lone queen attacks nothing.
  • n = 2[] — on a 2×2 board every pair of squares shares a row, column, or diagonal.

Constraints

  • 1 <= n <= 9 — solution counts stay small (352 for n=9), but the raw search space is enormous, so pruning row-by-row is the expected shape.

Think about it first

Hint 1 Every valid placement has exactly one queen per row. So instead of choosing 9 squares among 81, place queens row by row: the only decision for row `r` is *which column* gets the queen.
Hint 2 Placing row by row already rules out row conflicts. To reject a column choice instantly, keep three "occupied" sets: columns, one per diagonal direction. What single number identifies the ↘ diagonal through cell (r, c)? What identifies the ↙ diagonal?
Hint 3 Cells on the same ↘ diagonal share `r - c`; cells on the same ↙ anti-diagonal share `r + c`. Backtrack over rows: for each free column `c` in row `r` (i.e. `c`, `r-c`, `r+c` all unused), place, recurse to row `r+1`, then remove. When `r == n`, render the column list into board strings.

Write your solution, then hit Run tests to check it — or get a mock grade from the AI coach.

The coach remembers this session — revise your code and ask again, and it grades your progress. It gives hints, not the answer.
Report a bug