Practice
JavaScriptData StructuresReactConcepts
Sign in
← Back to problems

N-Queens (Count Solutions)

Recursion & Backtrackinghard

Implement `totalNQueens(n)` returning the number of distinct ways to place `n` queens on an `n × n` board so that no two attack each other (no shared row, column, or diagonal).

Examples

Input: n = 4
Output: 2
Input: n = 1
Output: 1

Sample tests

Input: totalNQueens(4)
Output: 2
Input: totalNQueens(1)
Output: 1

+ 2 hidden tests run on Submit.

Hints

Common pitfalls
  • Forgetting to undo the set additions after recursing (the backtracking step) corrupts later branches.

Learning resources

  • Wikipedia: Eight queens puzzle
Approach & explanation (try first)

Each row gets exactly one queen, so the search tries every safe column per row. Three sets give O(1) attack checks for columns and the two diagonal directions, and removing the marks on the way back out restores state for sibling branches. Counting completed placements yields the total.

Loading...
⌘/Ctrl + Enter

Run your code to see results.