ExamAdda Logo

N Queens II

Easy

Given an integer n, return the number of distinct solutions to the n-queens puzzle.

The n-queens puzzle asks you to place n queens on an n × n chessboard so that no two queens attack each other.

A queen can attack another queen if they are in the same:

  • Row
  • Column
  • Diagonal

You only need to return the total number of valid solutions, not the actual board arrangements.

Example 1

Input

n = 4

Output

2

Explanation

There are exactly 2 different ways to place 4 queens on a 4 × 4 board so that no two queens attack each other.

Example 2

Input

n = 1

Output

1

Explanation

A single queen can be placed on the only available square, so there is exactly one solution.

Constraints

1 <= n <= 9
There are n queens and an n × n chessboard.
No two queens can be in the same row.
No two queens can be in the same column.
No two queens can be on the same diagonal.

Hints:

Hint 1

Place exactly one queen in each row.

Hint 2

Before placing a queen at (row, col), check whether the column and both diagonals are already occupied.

Author & Technical Reviewer

ExamAdda Technical Review Team

Technically reviewed by: ExamAdda Technical Review Team

Technical Reviewers, ExamAdda

Software engineers at ExamAdda who check every article's definitions, complexity claims and code examples before and after publishing.

Published

Aug 21, 2026

Last updated

Aug 21, 2026

Content Verification Methodology

Definitions and complexity claims were checked against authoritative computer-science references. Code examples were compiled and tested with standard, boundary and edge-case inputs.

Report a correction:editorial@examadda.org
Auto
Loading editor...
Input

Expected Output