Skip to content
Preptima
hardCodingMidSeniorStaff

Count the ways to place N queens on an N by N board so that no two attack each other.

5 min readUpdated 2026-08-15Target archetype: Big Tech, Product Startup

Answer

Short answer

One queen per row is forced, so search row by row and keep sets of used columns, used sums and used differences to reject a conflict before recursing. The anti-diagonal is the row plus column and the main diagonal the row minus column, and that difference must be shifted into range, not reduced with an absolute value.

Was this answer helpful?

Likely follow-ups

  • Return one valid board instead of the count. What do you carry down the recursion?
  • Use the board's reflective symmetry to halve the work. What does it cost you in code clarity?
  • Some squares are blocked in advance. Where does that constraint enter?
  • Replace the three arrays with three bitmasks. What changes, and what stays exactly the same?

Related questions