Problem 52

Abstract / Summary

Count the number of ways to place n queens on an n by n chessboard so that no two queens attack each other.

Note

The full problem description, including helpful examples, can be found on LeetCode.

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;
    }
};

55 lines | 1394 bytes | submitted August 9, 2023 | GitHub   7% comment ratio | tab size 4

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 79% (700k+ submissions).

Typical patterns to solve this problem:
  • Backtracking
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
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.
LeetCode profile | GitHub repo

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.

written by openai gpt

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.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 6 | μ = 5.81 | σ = 1.70

Complexity Analysis

Time: factorial
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
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
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++
48 links | 32 authors | 9 languages

Videos

12 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

1 similar problem

Solved On The Same Day

10 easy 2 medium 15 hard
28 solutions   August 9, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • 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