InterviewPrepKit

Home / Coding / Backtracking

N-Queens II

hard Original β†—
Solving tips
  • Same row-by-row search as N-Queens I, but since only the count matters, carry no path and build no boards: reaching row n returns 1.
  • Track columns, r-c, and r+c conflicts; the minimal state that determines feasibility is all you need.
  • For speed, pack the three sets into integer bitmasks: free = full & ~(cols | diag | anti), peel candidates with free & -free, and shift diag<<1 / anti>>1 when descending a row.
  • Passing masks by value removes the explicit undo step (backtrack becomes stack unwinding); complexity stays O(n!) time, O(n) space. Do not divide by symmetry, and do not memoize.

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 = 4 β†’ 2 β€” the two mirror-image placements with queens in columns [1,3,0,2] and [2,0,3,1] (listed row by row).
  • n = 1 β†’ 1 β€” a single queen on the single square.
  • n = 3 β†’ 0 β€” on a 3Γ—3 board every third queen is always attacked; 2 and 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 actually search, and the count-only output invites a leaner state than building 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`.
Your workspace Not runnable by design β€” this is your interview scratchpad. Saved on this device.