N-Queens

hard

The N-Queens puzzle asks you to place n queens on an n x n chessboard so that no two queens attack each other. A queen attacks along its entire row, its entire column, and both diagonals.

Given an integer n, return all distinct ways to place the queens. You may return the boards in any order.

Each solution is a board drawn as n strings of length n, where 'Q' marks a queen and '.' marks an empty square.

Hints

Two queens in the same row always attack — so how many queens can a single row hold?
You're not choosing cells on a grid; you're choosing one column for each row. That's a much smaller decision.
Two cells lie on the same diagonal exactly when their row - col (or row + col) values match — turn each constraint into a set you can check in O(1).

Common doubts

'Q' marks a queen and '.' marks an empty square. Every board string is length n and uses only those two characters.
No. Any order of solutions is accepted; the judge normalizes before comparing, so focus on finding every distinct board.
There is no valid arrangement, so you return an empty list. The backtracking simply never reaches row == n.

Interview follow-ups

Return an integer and skip building strings — the same search, minus the board rendering. Bit masks over columns and diagonals make counting extremely fast.
Represent free columns and diagonals as bits in integers; each recursion shifts the diagonal masks, and you iterate only over set bits, removing all set and hashing overhead.

Fun facts

  • The 8-queens puzzle was posed in 1848 and later analyzed by Gauss; a standard chessboard admits exactly 92 solutions.
  • The 'one unit per row plus diagonal-as-a-key' pattern reappears in Sudoku solvers, Latin-square generation, and constraint-satisfaction engines everywhere.

Asked at

AmazonGoogleMicrosoftAdobe
Frequently Sometimes Occasionally
Example 1
Input: n = 4
Output: [[".Q..","...Q","Q...","..Q."],["..Q.","Q...","...Q",".Q.."]]
There are exactly two ways to place 4 non-attacking queens on a 4x4 board.
Example 2
Input: n = 1
Output: [["Q"]]
A single queen on a 1x1 board attacks nothing.
Constraints

- 1 <= n <= 9

Solve this problem →