15% off all plans & roadmaps Use code
See plansLeetCode 51 · Solution & editorial
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.
N-Queens is a Backtracking Patterns problem, in the N-Queens / Constraint Satisfaction subpattern. The pattern covers subsets, permutations, combinations, N-Queens, and word search
Solve N-Queens and Sudoku using backtracking with constraint propagation.
The reference solution runs in O(N!) time and O(N^2) space.
N-Queens has been reported in interviews at Facebook, Microsoft, Amazon, ByteDance, Apple, Adobe.
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 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.