HardBacktrackingAI interview only
N-Queens
Asked atgoogleamazonmetamicrosoftapplebloomberggoldman-sachs
01 · Problem
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.
02 · Examples
Example 01
Input
n = 4
Output
[[".Q..","...Q","Q...","..Q."],["..Q.","Q...","...Q",".Q.."]]
There are exactly two distinct solutions for placing 4 queens on a 4x4 board without conflicts.
Example 02
Input
n = 1
Output
[["Q"]]
A single queen on a 1x1 board is the only solution.
03 · Constraints
- 011 <= n <= 9
04 · Optimal complexity
- Time
- O(n!)
- Space
- O(n^2)
05 · Two ways to work on it
Practice it alone or rehearse it as an interview.
Practice Mode gives you an editor and test runs, nothing else. AI Interview Mode puts a voice interviewer on the other side, adds a clock, and ends with a scored summary of the round.