N-Queens (Count Solutions)

HardBacktrackingbacktracking

Solve this the way you would in the interview: out loud, on a timer, with an AI interviewer asking follow-ups while you code. You get a scored report at the end.

Practice this as a mock interviewFree to start, no account needed

Problem

You are given an n x n chessboard. Your task is to place exactly n queens on the board so that no two queens can attack each other. In chess, a queen attacks any piece that shares its **row**, its **column**, or either of its two **diagonals**. A placement is therefore valid only when every pair of queens differs in row, in column, and in both diagonal directions. Rather than listing the actual board arrangements, return the **total number of distinct valid placements** of n queens on the n x n board. Two placements are considered the same only if every queen sits on the identical square; reflections and rotations are counted as separate placements. Write a function that takes the integer n and returns the count of valid configurations.

Examples

Input: n = 4
Output: 2
On a 4x4 board there are exactly two ways to place 4 non-attacking queens (they are mirror images of each other, but both are counted).
Input: n = 1
Output: 1
A single queen on a 1x1 board has nothing to attack, so there is one valid placement.
Input: n = 8
Output: 92
The classic 8x8 chessboard admits 92 distinct arrangements of 8 non-attacking queens.

Constraints

  • 1 <= n <= 12
  • The board is always square with dimensions `n x n`.
  • Exactly `n` queens must be placed (one per row in any valid solution).

What the interviewer grades

A correct solution is one of five scores. The report also grades problem understanding (did you clarify inputs and edge cases before coding), problem solving, communication while you work, code quality, and testing. See a sample report, or read up on the pattern in the lessons.

More backtracking problems