15% off all plans & roadmaps Use code
See plansProblem editorial
Implement totalNQueens to count the distinct ways to place n queens on an n by n chessboard so that no two queens attack one another. Two queens attack one another if they share a row, column, or diagonal.
N-Queens II is a Backtracking Patterns problem, in the N-Queens / Constraint Satisfaction subpattern. The pattern covers subsets, permutations, combinations, N-Queens, and word search
The reference solution runs in O(n!) in the worst case, for the backtracking search. time and O(n) recursion stack space, excluding the integer bit masks. space.
The full editorial is part of Pro
It explains the core insight, the complexity analysis and the common mistakes, with a worked solution.
N-Queens II is a Backtracking Patterns problem, in the N-Queens / Constraint Satisfaction subpattern. Once the approach above makes sense, write it yourself and then work through the neighbouring problems that reuse it.