SDE & MLE Prep

52. N-Queens II

Problem

Return the number of distinct ways to place n non-attacking queens on an n×n chessboard.

Example: n = 4 → 2; n = 1 → 1

Constraints: n ≤ 9.

Count placements only. Bitmasks for columns and both diagonals: free = ~(cols | d1 | d2) & full; take the lowest bit each time; shift the diagonals by one when moving to the next row.

Complexity: O(n!), very fast in practice.

class Solution:
    def totalNQueens(self, n: int) -> int:
        full = (1 << n) - 1

        def bt(cols, d1, d2):
            if cols == full:
                return 1
            count, free = 0, ~(cols | d1 | d2) & full
            while free:
                bit = free & -free
                free -= bit
                count += bt(cols | bit, ((d1 | bit) << 1) & full, (d2 | bit) >> 1)
            return count

        return bt(0, 0, 0)