Tensorum
LeetCode 52 · Constraint Satisfaction

N-Queens II

LeetCode 52 · Hard · solution, intuition & step-by-step walkthrough

Backtracking that returns the number of solutions.

HardBacktrackingAlgorithm X
7 msruntime · beats 85%
19.3 MBmemory · beats 26%
1approach
6accepted runs · last 9 Mar 2026

This is how I solved N-Queens II (LeetCode 52), a hard problem from the Constraint Satisfaction pattern. Below: the intuition, the approach step by step, my accepted Python code, animated test cases and a line-by-line debugger.

Intuition

Same backtracking as N-Queens with O(1) attack checks, but return a count instead of building boards.

Approach

  1. 1

    Base: col == n → 1.

  2. 2

    Sum solutions over every safe row in this column.

  3. 3

    Mark/unmark the row and both diagonals around the recursion.

How I solved it

Counting backtrackingPythonO(n!) time
class Solution:
    def totalNQueens(self, n: int) -> int:
        board = [["."]*n for _ in range(n)]
        row_hash = [0]*n
        bottom_left_diagonal = [0]*(2*n-1)
        top_left_diagonal = [0]*(2*n-1)
        def backtrack(col,board):
            if col==n:
                return 1
            solutions = 0
            for row in range(n):
                if row_hash[row]==0 and bottom_left_diagonal[row+col]==0 and top_left_diagonal[n-1+col-row]==0:
                        board[row][col]="Q"
                        row_hash[row]=1
                        bottom_left_diagonal[row+col]=1
                        top_left_diagonal[n-1+col-row]=1
                        solutions+=backtrack(col+1,board)
                        board[row][col]="."
                        row_hash[row]=0
                        bottom_left_diagonal[row+col]=0
                        top_left_diagonal[n-1+col-row]=0
            return solutions
        return backtrack(0,board)
Loading the step-through…

N-Queens II — FAQ

What is the intuition behind N-Queens II?

Same backtracking as N-Queens with O(1) attack checks, but return a count instead of building boards.

How do you solve N-Queens II (LeetCode 52)?

1. Base: col == n → 1. 2. Sum solutions over every safe row in this column. 3. Mark/unmark the row and both diagonals around the recursion.

What is the time and space complexity of N-Queens II?

Time: O(n!). Space: O(n). (Accepted approach: Counting backtracking.)

What are common mistakes in N-Queens II?

The board array isn't needed for counting — the hashes are enough.