N-Queens - Problem

The n-queens puzzle is a classic problem of placing n queens on an n × n chessboard such that no two queens can attack each other.

In chess, a queen can attack any piece that lies in the same row, column, or diagonal as the queen.

Given an integer n, return all distinct solutions to the n-queens puzzle. Each solution should represent the board configuration where 'Q' indicates a queen and '.' indicates an empty space.

Input & Output

Example 1 — Classic 4-Queens
$ Input: n = 4
Output: [[".Q..","...Q","Q...","..Q."],["..Q.","Q...","...Q",".Q.."]]
💡 Note: For a 4×4 board, there are exactly 2 distinct solutions. First solution places queens at (0,1), (1,3), (2,0), (3,2). Second solution places queens at (0,2), (1,0), (2,3), (3,1). Both arrangements ensure no two queens can attack each other.
Example 2 — Simple 1-Queen
$ Input: n = 1
Output: [["Q"]]
💡 Note: For a 1×1 board, there's only one position and one queen, so the single solution is just placing the queen at (0,0).
Example 3 — Impossible Case
$ Input: n = 2
Output: []
💡 Note: For a 2×2 board, it's impossible to place 2 queens without them attacking each other. Any placement will result in queens being on the same row, column, or diagonal.

Constraints

  • 1 ≤ n ≤ 9

Visualization

Tap to expand
N-Queens Problem: Place n=4 Queens Without ConflictsInput: n = 444×4 board4 queensValid Solution 1Valid Solution 2Queen Attack Patterns: Same Row, Column, or Diagonal❌ Invalid PlacementsSame row❌ Invalid PlacementsSame column❌ Invalid PlacementsSame diagonalOutput: Array of valid board configurations (2 solutions for n=4)Each solution is array of strings: [".Q..", "...Q", "Q...", "..Q."]
Understanding the Visualization
1
Input
Integer n representing board size and number of queens
2
Constraint
No two queens can attack each other (same row, column, or diagonal)
3
Output
All possible board configurations as string arrays
Key Takeaway
🎯 Key Insight: Use backtracking with constraint checking to efficiently explore only valid paths
Asked in
Google 45 Amazon 38 Microsoft 32 Apple 28
156.0K Views
Medium Frequency
~25 min Avg. Time
2.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