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 INPUT 4x4 Chessboard n = 4 Queen attacks: Row, Column, Diagonals Q ALGORITHM STEPS 1 Start Row 0 Try placing Q in each col 2 Check Safety No attacks from prev Qs 3 Recurse Next Row If safe, move to row+1 4 Backtrack If stuck, try next col Backtracking Tree: X OK OK X FINAL RESULT Solution 1: Q Q Q Q Solution 2: Q Q Q Q [".Q..","...Q","Q...","..Q."] ["..Q.","Q...","...Q",".Q.."] 2 Valid Solutions Found! Complexity: Time: O(N!) Space: O(N^2) Key Insight: Use backtracking to explore all possible queen placements row by row. At each row, try placing a queen in each column and check if it's safe (no conflicts with previous queens). Track columns, left diagonals (row-col), and right diagonals (row+col) to efficiently validate placements in O(1) time. TutorialsPoint - N-Queens | Backtracking Approach
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