N-Queens II - Problem

The N-Queens puzzle is a classic backtracking problem where you need to place n chess queens on an n × n chessboard such that no two queens can attack each other.

Two queens attack each other if they are:

  • On the same row
  • On the same column
  • On the same diagonal (both main diagonal and anti-diagonal)

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

Input & Output

Example 1 — Small Board
$ Input: n = 4
Output: 2
💡 Note: There are exactly 2 distinct solutions for a 4×4 board. Solution 1: queens at positions (0,1), (1,3), (2,0), (3,2). Solution 2: queens at positions (0,2), (1,0), (2,3), (3,1).
Example 2 — Minimal Board
$ Input: n = 1
Output: 1
💡 Note: For n=1, there's only one cell on the board, so exactly 1 solution: place the single queen at position (0,0).
Example 3 — Impossible Case
$ Input: n = 2
Output: 0
💡 Note: On a 2×2 board, it's impossible to place 2 queens without them attacking each other. Any placement results in queens sharing a row, column, or diagonal.

Constraints

  • 1 ≤ n ≤ 9

Visualization

Tap to expand
N-Queens II - Backtracking Solution INPUT 4x4 Chessboard n = 4 Board size No two queens can attack each other (row, col, diagonal) ALGORITHM STEPS 1 Initialize Sets cols, diag1, diag2 2 Try Each Column For current row 3 Check Conflicts col, row-col, row+col 4 Backtrack Remove and try next Set Tracking cols = {} diag1 = {} (r-c) diag2 = {} (r+c) O(1) conflict check FINAL RESULT Solution 1 Solution 2 Output: 2 Key Insight: Using sets for columns and diagonals enables O(1) conflict detection. Diagonal identification: same (row-col) means same "/" diagonal, same (row+col) means same "\" diagonal. This optimization reduces time complexity compared to checking all placed queens. Total solutions grow factorially. TutorialsPoint - N-Queens II | Optimized Backtracking with Sets
Asked in
Google 25 Amazon 20 Microsoft 15 Apple 10
125.0K Views
Medium Frequency
~15 min Avg. Time
1.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen