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)

One problem, two ways to prep

Choose between solo practice and interview simulation

Practice Mode keeps things simple with code + tests. AI Interview Mode adds voice, pressure, and a post-round score summary.