HARD NC#79 Backtracking

51. N-Queens

๐Ÿ“– 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.

๐Ÿง  Visual Learning Aid

1 Model the input into the right structure
2 Choose the core technique and invariant
3 Execute step-by-step with a sample
4 Validate complexity and edge cases

JS/TS Refreshers

  • โ€ขArray methods (`push`, `pop`, `shift`, `slice`)
  • โ€ขObject/Map/Set usage patterns
  • โ€ขFunction parameter and return typing
  • โ€ขRecursive function frames
  • โ€ขPush/pop state undo
  • โ€ขPruning branches early

Logical Thinking Concepts

  • โ€ขDefine invariants before coding
  • โ€ขCheck edge cases first (`[]`, single element, duplicates)
  • โ€ขEstimate time/space before implementation
  • โ€ขApply Backtracking reasoning pattern
  • โ€ขApply Recursion reasoning pattern

๐Ÿ’ก Approach

  • โ†’ Use backtracking to try each valid queen position
  • โ†’ Track used columns and diagonals to avoid attacks
  • โ†’ For each row, try placing queen at each column
  • โ†’ Skip invalid positions (conflicts)
  • โ†’ Time: O(N!), Space: O(N) for recursion stack

๐Ÿ› ๏ธ Hints & Pitfalls

Hints

  • โ€ขUse backtracking to try each valid queen position
  • โ€ขTrack used columns and diagonals to avoid attacks
  • โ€ขFor each row, try placing queen at each column

Common Pitfalls

  • โ€ขSkip invalid positions (conflicts)
  • โ€ขTime: O(N!), Space: O(N) for recursion stack

๐Ÿงช Test Cases

Hidden tests on submit: 1

Test Case 1
Not run
Input:
solveNQueens(4);
Expected:
[[".Q..","...Q","Q...","..Q."], ["..Q.","Q...","...Q",".Q.."]]
Test Case 2
Not run
Input:
solveNQueens(1);
Expected:
[["Q"]]
Test Case 3
Not run
Input:
solveNQueens(3);
Expected:
[]

๐Ÿ“ Code Editor

๐Ÿ“š Reference Solution

โ–ผ
โŒ˜K Search โŒ˜โ†ฉ Run โŒ˜S Submit