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
๐งญ Prerequisites
๐ ๏ธ 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
๐ค Output