N Queen

Recursion FAQs (Hard) Hard

The challenge of arranging n queens on a n × n chessboard so that no two queens attack one another is known as the "n-queens puzzle."


Return every unique solution to the n-queens puzzle given an integer n. The answer can be returned in any sequence.


Every solution has a unique board arrangement for the placement of the n-queens, where 'Q' and '.' stand for a queen and an empty space, respectively.

Examples:

Input : n = 4

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

Explanation : There are two possible combinations as shown below.


Input : n = 2

Output : [ [] ]

Explanation : There is no possible combination for placing two queens on a board of size 2*2.

Input : n = 1

Constraints

  • 1 <= n <= 9

Hints

  • Use backtracking to try placing queens row by row.
  • Use sets to efficiently track conflicts in columns, main diagonals, and anti-diagonals. Prune invalid branches early to reduce unnecessary computations.

Company Tags

Morgan Stanley Zoho Deloitte Robinhood Stripe Philips Healthcare Electronic Arts GE Healthcare Texas Instruments NVIDIA PwC Qualcomm Broadcom Mastercard Western Digital IBM Cloudflare JPMorgan Chase Lyft Roblox Bungie Snowflake Dropbox Seagate Technology HashiCorp Google Microsoft Amazon Meta Apple Netflix Adobe