N-Queens
On this page
Problem statement
Place n queens on an n × n chessboard so that no two queens attack each other: no two may share a row, a column or a diagonal. Return every distinct arrangement, each as a list of n strings where
Qmarks a queen and.an empty square.
The classic backtracking problem. It tests whether you can turn "try everything" into a search that rules out bad choices early, and whether you can express "same diagonal" in one line. Original problem: LeetCode 51.
Example

Input: n = 4
Output: [[".Q..",
"...Q",
"Q...",
"..Q."],
["..Q.",
"Q...",
"...Q",
".Q.."]]
Input: n = 3
Output: [] # no arrangement exists for n = 2 or 3
Constraints (assumed)
- 1 ≤ n ≤ 9 (the number of solutions grows fast: 92 for n = 8, 352 for n = 9).
What this question tests
- Structuring a backtracking search: one decision per row, recurse, undo.
- Encoding the constraints so each safety check is O(1): a column set and two diagonal sets keyed by
r − candr + c. - Building the output cleanly without copying the whole board at every step.
Questions to ask first
- All solutions, or just how many? (Here: all boards. Counting is the N-Queens II follow-up.)
- Does the order of solutions matter? (Here: no.)
- Do rotations and reflections count as different solutions? (Here: yes.)
- How big can n get? Exponential search is fine up to about 12–14.
Try it yourself first
You have the full problem. Sketch your answer, then sign up free to read the complete walkthrough.
- The complete design, flow by flow, with pictures
- Deep dives into the hard parts
- What mid, senior and staff candidates are expected to say
- Full company question lists
Free forever. No card needed.