C++ 0052.cpp
class Solution {
public:
int totalNQueens(int n) {
// see problem 51, even simpler
vector<int> order;
for (int i = 0; i < n; i++)
order.push_back(i);
int result = 0;
do
{
int blockLeft = 0;
int blockRight = 0;
bool ok = true;
int line;
for (line = 0; line < order.size(); line++)
{
int pos = order[line];
int mask = 1 << pos;
ok &= (mask & blockLeft) == 0;
ok &= (mask & blockRight) == 0;
blockLeft <<= 1;
blockRight >>= 1;
blockRight &= (1 << n) - 1;
if (!ok)
break;
blockLeft |= mask << 1;
blockRight |= mask >> 1;
}
if (ok)
result++;
else
{
// skip permutations
if (line < n - 1)
{
// not perfect, but fast
sort (order.begin() + line + 1, order.end());
reverse(order.begin() + line + 1, order.end());
}
}
} while (next_permutation(order.begin(), order.end()));
return result;
}
};
Difficulty
and has an acceptance rate of about 79% (700k+ submissions).
Typical patterns to solve this problem:
- Backtracking
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The presented implementation solves the classic N-Queens counting problem by enumerating all possible column permutations for the rows of an n × n board. Each permutation represents a placement where exactly one queen occupies each row and each column. The algorithm then validates whether any two queens share a diagonal. Valid configurations increment a result counter, and the search space is pruned by reordering the remaining suffix of the permutation when a conflict is detected.
Key Steps
The algorithm begins by constructing a vector that holds the natural order of column indices.
vector<int> order;
for (int i = 0; i < n; i++)
order.push_back(i);
A loop driven by next_permutation iterates over every possible ordering of columns. Inside the loop, two bit masks, blockLeft and blockRight, track the diagonals that are already occupied as the algorithm scans rows from top to bottom.
int blockLeft = 0;
int blockRight = 0;
bool ok = true;
int line;
for (line = 0; line < order.size(); line++)
{
int pos = order[line];
int mask = 1 << pos;
ok &= (mask & blockLeft) == 0;
ok &= (mask & blockRight) == 0;
blockLeft <<= 1;
blockRight >>= 1;
blockRight &= (1 << n) - 1;
if (!ok)
break;
blockLeft |= mask << 1;
blockRight |= mask >> 1;
}
During each iteration of the inner loop, the current column pos is transformed into a single-bit mask. The mask is tested against the two diagonal masks; a non-zero intersection indicates a conflict. If a conflict occurs, the loop exits early, leaving ok false.
When the inner loop finishes without conflict, the current permutation represents a legal queen placement and the result counter is increased.
if (ok)
result++;
If a conflict is found before the last row, the algorithm performs a targeted reordering of the remaining suffix of the permutation. This step rearranges the suffix into its highest lexicographic order, causing the subsequent next_permutation call to skip a large block of invalid permutations.
if (line < n - 1)
{
sort (order.begin() + line + 1, order.end());
reverse(order.begin() + line + 1, order.end());
}
The outer do … while loop continues until all permutations have been examined. Finally, the accumulated count is returned.
return result;
Edge Cases Handled
The code gracefully handles the situation where n equals zero. In that case the initial vector is empty, the do block executes once, the inner loop does not run, ok remains true, and the function returns 1, which matches the combinatorial definition that there is exactly one way to place zero queens.
When n is one, the vector contains a single element 0. The diagonal masks are initially zero, the mask for the sole queen is 1, and both diagonal checks succeed. The result becomes 1, correctly reflecting the single valid configuration.
For larger n, the bit-mask operations automatically truncate any overflow beyond the board width by applying blockRight &= (1 << n) - 1;. This ensures that right-shifted bits that would otherwise spill outside the board are discarded, preserving correctness for any board size that fits within the width of an int.
The early break on conflict (if (!ok) break;) prevents unnecessary processing of the remaining rows once a diagonal clash is detected, which is essential for correctness when the permutation does not represent a valid solution.
Performance Optimizations
The algorithm leverages several techniques to reduce the effective search space.
First, the use of bit masks for diagonal occupancy enables constant-time conflict detection per row, avoiding nested loops over previously placed queens.
Second, the inner loop updates the diagonal masks incrementally: left-diagonal mask is shifted left, right-diagonal mask is shifted right, and then the current queen’s influence is added by left-shifting or right-shifting the current column mask. This incremental approach eliminates the need to recompute diagonal coverage from scratch for each row.
Third, the early exit on conflict (break) stops the scan as soon as a diagonal violation is found, preventing the algorithm from performing unnecessary mask updates for the remaining rows of the current permutation.
Fourth, when a conflict occurs before the final row, the suffix of the permutation is reordered into descending order via a sort followed by a reverse. This transformation forces the next call to next_permutation to jump over all permutations that share the same prefix, effectively pruning an entire subtree of the permutation tree that would inevitably contain the same conflict pattern.
Finally, the outer loop uses do … while (next_permutation(...)), which iterates over permutations in lexicographic order. Combined with the suffix reordering, this ordering ensures that the algorithm explores only the necessary branches of the permutation space, yielding a practical speedup compared with a naïve exhaustive enumeration.
ELI5 - Simplified Explanation
Imagine a chessboard where the goal is to place queens so that they do not bother each other. A queen is very powerful and can attack any spot in the same row, column, or diagonal line. To solve this, the code starts by putting one queen in every row, making sure no two queens are in the same column. It creates a list of numbers to represent where each queen stands.
The code then tries every possible arrangement of these queens. For each arrangement, it checks if any queens have a diagonal path that crosses another queen. It uses two special tools called masks to keep track of the dangerous paths created by the queens already placed. Think of these masks as shadows moving across the board whenever a new queen is placed. If a queen is found in a spot that is already covered by a shadow, the code marks that try as not okay and stops looking at that specific path.
If the check succeeds and no queens are clashing, the count of valid boards goes up by one. If a clash happens, the code skips ahead to try a different arrangement based on the queen that caused the trouble. By shuffling the order of the queens over and over again until all combinations are tested, the code counts how many ways exist to place every queen safely.
Code Quality
Complexity Analysis
As a rule of thumb, the maximum input size for one second execution time is
- factorial: up to 10 elements
- exponential: up to 20 elements
- polynomial: a few thousand elements
- loglinear: up to 100,000 elements
- linear: a few million elements
- logarithmic: a billion elements
- constant: practically unlimited
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | ||||||||||
|---|---|---|---|---|---|---|---|---|---|---|
| author | solutions | |||||||||
| www | AlgoMonster | C++ | Python | Java | TS | |||||
| WalkCCC | C++ | Python | Java | |||||||
| leetcode.ca | C++ | Python | C# | JS | Java | Go | TS | |||
| LeetcodeHelp | C++ | Python | Java | |||||||
| MemoryLimitExceeded | C++ | Python | ||||||||
| Progiez | C++ | Python | Java | |||||||
| github | aylei | Rust | ||||||||
| begeekmyfriend | C | |||||||||
| BigEggStudy | C# | |||||||||
| black-shadows | Python | |||||||||
| charles-wangkai | Java | |||||||||
| chenyanzhe | C++ | |||||||||
| everthis | JS | |||||||||
| fpdjsns | C++ | |||||||||
| gaosq0604 | Python | |||||||||
| halfrost | Go | |||||||||
| JoshCrozier | JS | |||||||||
| keineahnung2345 | C++ | |||||||||
| lennylxx | C | |||||||||
| linouk23 | C++ | |||||||||
| lkwq007 | Python | |||||||||
| luangong | C++ | |||||||||
| MacJim | C++ | |||||||||
| qiyuangong | Python | |||||||||
| ruoru | Rust | |||||||||
| shreymehul | C# | |||||||||
| suxrobGM | C# | |||||||||
| trung-hn | Python | |||||||||
| varunu28 | Java | |||||||||
| vli02 | C | |||||||||
| XiaotaoGuo | C++ | |||||||||
| zfang399 | C++ | |||||||||
| AlgoMonster | C++, Python, Java, TypeScript | |||||||||
| WalkCCC | C++, Python, Java | |||||||||
| leetcode.ca | C++, C#, Go, Java, JavaScript, Python, TypeScript | |||||||||
| LeetcodeHelp | C++, Java, Python | |||||||||
| MemoryLimitExceeded | Python, C++ | |||||||||
| Progiez | C++, Java, Python | |||||||||
| aylei | Rust | |||||||||
| begeekmyfriend | C | |||||||||
| BigEggStudy | C# | |||||||||
| black-shadows | Python, Python | |||||||||
| charles-wangkai | Java | |||||||||
| chenyanzhe | C++ | |||||||||
| everthis | JavaScript | |||||||||
| fpdjsns | C++ | |||||||||
| gaosq0604 | Python | |||||||||
| halfrost | Go | |||||||||
| JoshCrozier | JavaScript | |||||||||
| keineahnung2345 | C++ | |||||||||
| lennylxx | C | |||||||||
| linouk23 | C++ | |||||||||
| lkwq007 | Python | |||||||||
| luangong | C++ | |||||||||
| MacJim | C++ | |||||||||
| qiyuangong | Python | |||||||||
| ruoru | Rust | |||||||||
| shreymehul | C# | |||||||||
| suxrobGM | C# | |||||||||
| trung-hn | Python | |||||||||
| varunu28 | Java | |||||||||
| vli02 | C | |||||||||
| XiaotaoGuo | C++ | |||||||||
| zfang399 | C++ |
Videos
Similar Problems
- problem 51: N-Queens
Solved On The Same Day
- problem 125: Valid Palindrome
- problem 191: Number of 1 Bits
- problem 202: Happy Number
- problem 217: Contains Duplicate
- problem 219: Contains Duplicate II
- problem 290: Word Pattern
- problem 383: Ransom Note
- problem 392: Is Subsequence
- problem 1047: Remove All Adjacent Duplicates In String
- problem 1089: Duplicate Zeros
- problem 151: Reverse Words in a String
- problem 187: Repeated DNA Sequences
- problem 51: N-Queens
- problem 60: Permutation Sequence
- problem 68: Text Justification
- problem 76: Minimum Window Substring
- problem 135: Candy
- problem 140: Word Break II
- problem 220: Contains Duplicate III
- problem 239: Sliding Window Maximum
- problem 352: Data Stream as Disjoint Intervals
- problem 502: IPO
- problem 895: Maximum Frequency Stack
- problem 982: Triples with Bitwise AND Equal To Zero
- problem 995: Minimum Number of K Consecutive Bit Flips
- problem 996: Number of Squareful Arrays
- problem 2136: Earliest Possible Day of Full Bloom
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality