N Queens II
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
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
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.
Expected Output