Skip to main content
All Questions

Print all possible solutions to the N-Queens problem.

Hard
Unlock detailed company stats for this questionUpgrade

Place n queens on an n x n chessboard so that no two queens attack each other. A queen attacks every square in its row, its column and both of its diagonals.

Return every distinct arrangement. Write each board as a list of n strings, one per row, where "Q" marks a queen and "." marks an empty square. The boards can be in any order.

Example 1

Input: n = 4 Output: [[".Q..", "...Q", "Q...", "..Q."], ["..Q.", "Q...", "...Q", ".Q.."]]

A 4 x 4 board has exactly two arrangements, and each is the mirror image of the other.

Example 2

Input: n = 3 Output: []

No arrangement works on a 3 x 3 board.

Constraints

  • 1 <= n <= 9

Related courses

Course

Data Engineering Interview Prep

Land your dream data engineering role at Meta, Google, Amazon, Microsoft, Walmart, DoorDash, and other top companies. Learn from mock interviews, frameworks, and advice from senior candidates. Practice data modeling, pipeline design, SQL, coding, behavioral interviews, and more.

Course

Software Engineering Interview Prep

Land your dream software engineering role at Google, Amazon, Microsoft, Meta, Apple, and other top companies. Learn from mock interviews, frameworks, and advice from senior candidates—practice data structures, algorithms, system design, people management, behavioral interviews, and more.