All problems
HardBacktracking

N-Queens

googleamazonmetamicrosoftapplebloomberggoldman-sachs

The n-queens puzzle is the problem of placing n queens on an n x n chessboard such that no two queens attack each other.

Given an integer n, return all distinct solutions to the n-queens puzzle. You may return the answer in any order.

Each solution contains a distinct board configuration of the n-queens' placement, where 'Q' and '.' both indicate a queen and an empty space, respectively.

Example 1:

Input: n = 4
Output: [[".Q..","...Q","Q...","..Q."],["..Q.","Q...","...Q",".Q.."]]
Explanation: There exist two distinct solutions to the 4-queens puzzle.

Example 2:

Input: n = 1
Output: [["Q"]]
Explanation: There is only one way to place a single queen on a 1x1 board.

Examples

Example 1

Input: n = 4

Output: [[".Q..","...Q","Q...","..Q."],["..Q.","Q...","...Q",".Q.."]]

Explanation: There are exactly two distinct solutions for placing 4 queens on a 4x4 board without conflicts.

Example 2

Input: n = 1

Output: [["Q"]]

Explanation: A single queen on a 1x1 board is the only solution.

Constraints

  • -1 <= n <= 9

Optimal Complexity

Time

O(n!)

Space

O(n^2)

Practice this problem with an AI interviewer

TechInView conducts a full voice mock interview — the AI asks clarifying questions, evaluates your approach, watches you code, and scores you on 5 dimensions. Just like a real FAANG interview.

Start a free interview