A chess queen attacks any square in the same row, the same column, or on either diagonal. Given a board size n, you want to put n queens on an n × n board so that none of them can attack another.
Return how many different placements achieve that. You only report the number, not the boards.
Example 1
Input: n = 5 Output: 10 Why: ten placements of five queens are attack-free
2 more examples and the constraints
Example 2
Input: n = 3 Output: 0 Why: the queen in the middle row is always attacked
Example 3
Input: n = 6 Output: 4 Why: a bigger board can still have fewer answers
Constraints
- 1 ≤ n ≤ 9
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Try every column orderO(n!·n²)
- Backtracking with attack setsO(n!)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for n = 9 | Verdict |
|---|---|---|---|
| Try every column order | O(n!·n²) | Correct, but checks every full board | |
| Backtracking with attack sets | O(n!) | Best; prunes as it places |
n = the board size. Backtracking only visits partial boards that are still safe, far fewer than n!.
Edge cases to test
- n = 1. A single queen on a single square is one valid placement: return 1.
- n = 2 and n = 3. No placement works, so the count is 0.
- Negative diagonal keys. r − c goes below zero. Sets are fine with that; arrays need an offset such as + n.
- Largest board. n = 9 has 352 placements, small enough that the count never overflows.
Common mistakes
- Checking only one diagonal direction. Both r − c and r + c must be free.
- Forgetting to remove the queen from the sets after the call returns, so later rows see a queen that is gone.
- Counting with a shared variable but also returning a value, and adding the same board twice.
How to talk through it
- 1Clarify. Do you want the boards or only how many there are? Are mirror images counted separately?
- 2Shrink the search. One queen per row and per column, so a board is just a column order: n! candidates.
- 3Prune early. Check each queen as it goes down, using three sets: columns, r − c and r + c.
- 4Code the backtracking. Place, recurse and add up the returned counts, then undo. Point at the undo.
- 5Test out loud. n = 1 gives 1, n = 2 and n = 3 give 0, n = 4 gives 2.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?