N-Queens
Problem
Place n queens on an n x n chessboard so that no two queens threaten each other; queens attack along rows, columns, and both diagonals. Return every distinct arrangement. Each arrangement is a list of n strings, one per row, using 'Q' for a queen and '.' for an empty square. Output order does not matter.
- The board size n is between 1 and 10.
Examples
n = 4→[[".Q..","...Q","Q...","..Q."], ["..Q.","Q...","...Q",".Q.."]]. Exactly two arrangements exist, mirror images of each other.n = 1→[["Q"]]. A single queen on a single square.n = 3→[]. No valid arrangement exists for n = 2 or n = 3.
Hints
- Every row must contain exactly one queen. So a solution is just a choice of one column per row; you do not need to consider arbitrary square subsets.
- Placing a queen at
(r, c)rules out columnc, the diagonal wherer - cis constant, and the anti-diagonal wherer + cis constant. Can you check those in O(1)? - Backtrack row by row, keeping three sets (columns,
r - c,r + c); place, recurse, remove.
Last reviewed 8 September 2026
Approach · Solution (Python) · Complexity · Follow-ups · Company variations · Tests
The rest of this question — the worked approach, the Python solution with passing tests, complexity, follow-ups and how each company frames it — is part of the guides.
Get the full guide
Pick the company you're interviewing with. Each guide has every question tiered for that loop — one-time purchase, lifetime access.
Also in: Apple, Google, Meta, Microsoft, Netflix
Interviewing at more than one? All 6 guides for $499 · save $395
Not ready to buy? Get the free starter pack — 13 questions with full solutions.