N Queen

Recursion FAQs (Hard) Hard
  • The N-Queens problem, while initially appearing as just a chess puzzle, actually has valuable implications in real-world applications
  • Its solution relies on a fundamental concept in technology: backtracking, which is used in recommendation algorithms, routing protocols, database queries optimizations and more
  • Any time you need to make a series of decisions, where each decision leads to a new set of choices, backtracking becomes a handy tool
  • The principles of this problem are even applied in branches of artificial intelligence for constraint satisfaction problems such as scheduling, map-coloring and Sudoku

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