InterviewPrepKit

Home / Coding / Algorithm & Data Structure / Backtracking

N-Queens II

hard Original ↗ 00:00

Problem

Given an integer n, return how many distinct ways n chess queens can be placed on an n x n board so that no two attack each other — no shared row, column, or diagonal. Unlike N-Queens I, you do not output the boards, only their count.

Examples

  • n = 42 — the two mirror-image placements with queens in columns [1,3,0,2] and [2,0,3,1] (listed row by row).
  • n = 11 — a single queen on the single square.
  • n = 30 — no valid placement exists; n = 2 and n = 3 are the only sizes above 1 with no solution.

Constraints

  • 1 <= n <= 9 — the answer for n = 9 is 352. There is no closed-form formula, so you must search. Because only the count is required, the state can be leaner than one that builds boards.

Think about it first

Hint 1 Solve N-Queens I first: place queens row by row, tracking used columns and both diagonal directions (`r - c` and `r + c`). What changes when only the count is needed?
Hint 2 Drop the path entirely — no column list, no board rendering. When the row index reaches `n`, add 1. The recursion needs nothing but the three conflict sets.
Hint 3 With `n <= 9`, all three sets fit in one machine word each: bit `c` of a `cols` mask, plus a `diag` mask and an `anti` mask expressed *relative to the current row* — shift `diag` left and `anti` right as you descend one row. Free squares of the row are `full & ~(cols | diag | anti)`; peel candidates with `free & -free`.

Write your solution, then hit Run tests to check it — or get a mock grade from the AI coach.

The coach remembers this session — revise your code and ask again, and it grades your progress. It gives hints, not the answer.
Report a bug