N-Queens solution explained

N-Queens asks for every way to place n chess queens on an n × n board so that no two share a row, column or diagonal. The standard solution places one queen per row with backtracking and keeps three sets, for used columns, used "row minus column" diagonals and used "row plus column" diagonals, so each safety check is O(1). The search is exponential, roughly bounded by O(n!), but pruning makes it fast for the board sizes interviews use.

By Published 9 min read

The puzzle in plain terms

A queen attacks any square in its row, its column, or either of its two diagonals, at any distance. Given a number n, find every arrangement of n queens on an n × n board in which no queen attacks another. Each arrangement is usually returned as n strings, one per row, with Q for a queen and a dot for an empty square. A common variant asks only for how many arrangements exist.

. Q . .      . . Q .
. . . Q      Q . . .
Q . . .      . . . Q
. . Q .      . Q . .
The two solutions for a 4 × 4 board (one is the mirror image of the other)

Small cases worth knowing: a 1 × 1 board has one solution, 2 × 2 and 3 × 3 have none, 5 × 5 has ten, 6 × 6 has four, and the classic 8 × 8 board has 92. You do not need to memorize them, but the fact that 6 has fewer than 5 is a nice sanity check that the counts are not monotonic, and quoting n = 4 lets you test your code on the spot.

Why it gets asked

N-Queens is the textbook example of pruning. A candidate who places queens anywhere and checks at the end will produce something correct but hopeless. The interviewer is watching for three ideas, in order: put exactly one queen in each row, so rows take care of themselves; check column and diagonal conflicts as you place, not afterward; and make that check constant time by encoding diagonals as r − c and r + c. Senior candidates are often asked to go one step further with bitmasks.

The crudest brute force picks any n of the n² squares, which is astronomically many sets even for n = 8. A much better one uses the structure: every valid board has exactly one queen per row and one per column, so a solution is a permutation of the columns. Try all n! permutations and keep those where no two queens share a diagonal. That is O(n! · n²) with a pairwise check and is a useful reference for testing, but it still generates every permutation before rejecting it.

from itertools import permutations


def count_queens_slow(n):
    total = 0
    for cols in permutations(range(n)):
        if all(abs(cols[a] - cols[b]) != b - a
               for a in range(n) for b in range(a + 1, n)):
            total += 1
    return total
Python reference: every column permutation, filtered by diagonals. For testing only.

Backtracking builds the permutation one row at a time and stops the moment a partial placement fails. If the queen in row 1 already clashes with the queen in row 0, no completion of that prefix is explored at all. That early cut is where nearly all the speed comes from.

Backtracking with three sets

Process rows from top to bottom. For the current row, try each column. A square (r, c) is safe if column c is unused, the diagonal running down and to the right through it is unused, and the diagonal running down and to the left is unused. Every square on a down-right diagonal has the same value of r − c, and every square on a down-left diagonal has the same r + c, so those two numbers name the diagonals. Place the queen by adding c, r − c and r + c to their sets, recurse to the next row, then remove them. When the row index reaches n, record the board.

def solve_n_queens(n):
    boards = []
    queen_col = [0] * n          # queen_col[r] = column of the queen in row r
    cols, downs, ups = set(), set(), set()

    def place(r):
        if r == n:
            boards.append(["." * c + "Q" + "." * (n - c - 1) for c in queen_col])
            return
        for c in range(n):
            if c in cols or (r - c) in downs or (r + c) in ups:
                continue
            queen_col[r] = c
            cols.add(c); downs.add(r - c); ups.add(r + c)
            place(r + 1)
            cols.remove(c); downs.remove(r - c); ups.remove(r + c)

    place(0)
    return boards
Python: one queen per row, sets for columns and both diagonals, boards built at the leaves.

Storing only the column of each row's queen keeps the state tiny. The board strings are built only when a full solution is found, so failed branches never pay for string work. Recursion depth is n, which is small here.

Counting with bitmasks

For the counting variant, the three sets can become three integers whose bits mark blocked columns for the current row. The trick is that diagonal threats shift as you move down: a queen's down-right threat moves one column right per row, and its down-left threat moves one column left. So when you go to the next row, shift the down-right mask left by one and the down-left mask right by one (or the reverse, depending on which end you call column 0). The free squares are the zero bits of the three masks combined, and the lowest free bit is isolated with x & −x.

function countNQueens(n) {
  const full = (1 << n) - 1;
  let count = 0;
  const go = (cols, diagL, diagR) => {
    if (cols === full) {
      count++;
      return;
    }
    let free = full & ~(cols | diagL | diagR);
    while (free !== 0) {
      const bit = free & -free;   // lowest free column
      free ^= bit;
      go(cols | bit, ((diagL | bit) << 1) & full, (diagR | bit) >> 1);
    }
  };
  go(0, 0, 0);
  return count;
}
JavaScript: count solutions with bitmasks. JavaScript bit operators work on 32-bit integers, which covers n up to 30, far past any size that finishes quickly.
def count_n_queens(n):
    full = (1 << n) - 1

    def go(cols, diag_l, diag_r):
        if cols == full:
            return 1
        total = 0
        free = full & ~(cols | diag_l | diag_r)
        while free:
            bit = free & -free
            free ^= bit
            total += go(cols | bit, ((diag_l | bit) << 1) & full, (diag_r | bit) >> 1)
        return total

    return go(0, 0, 0)
Python: the same bitmask counter, for comparison with the set version.

The & full after the left shift keeps bits from walking off the edge of the board and growing the integer. The right shift drops bits off the other edge on its own. A small optimization people mention: by mirror symmetry, you can count only placements whose first-row queen sits in the left half, double that, and handle the middle column separately for odd n. It roughly halves the work, but get the plain version right first.

Complexity

n is the board size; S is the number of solutions
ApproachTimeExtra space
All column permutations, checked afterO(n! · n²)O(n)
Backtracking, scanning earlier queens to checkUnder O(n! · n) in practice, with pruningO(n)
Backtracking with three setsUnder O(n!), plus O(S · n²) to build boardsO(n) besides the output
Bitmask countingSame search tree, much smaller constantO(n) recursion
n is the board size; S is the number of solutions. Scroll sideways on a small screen.

No neat closed-form bound is expected. The honest answer is that the first row has n choices, the second at most n − 1 safe ones, and so on, so the tree has fewer than n! leaves, and pruning on the diagonals cuts it much further. Building each output board costs O(n²), which is why S · n² appears for the listing version.

Edge cases

  • n = 1: one board, ["Q"].
  • n = 2 and n = 3: an empty list, not an error.
  • n = 4: exactly the two boards above, a quick check of your diagonal math.
  • Larger n in the counting version, where bitmasks and avoiding board strings matter.

Typical bugs

  • Encoding only one diagonal direction and returning boards where queens attack along the other.
  • Using r − c as a list index without an offset; in some languages that is a negative index, and in Python it silently reads from the end.
  • Forgetting to remove a queen from all three sets on the way back.
  • Building board strings at every step instead of once per solution.
  • Shifting both diagonal masks the same way in the bitmask version.

How to talk through it

Fictional example

Narrating the key ideas in order
Candidate
Every solution has one queen per row, so I will recurse row by row and choose a column for each. That removes row conflicts entirely.
Candidate
For columns I keep a set. For diagonals, squares on the same down-right diagonal share row minus column, and squares on the same down-left diagonal share row plus column, so two more sets make each check constant time.
Candidate
I only store the column per row and build the strings when I finish a board. Let me trace n equals four: the first queen in column 0 dead-ends, column 1 leads to a solution.
Interviewer
Could you make the count faster?
Candidate
Yes, with three integers as bitmasks. Free columns are the zero bits, I take the lowest one each time, and the diagonal masks shift by one as I move down a row.

The same place-and-undo loop with a much looser constraint appears in Letter Combinations of a Phone Number. Palindrome Partitioning adds a precomputed table to speed up its checks, much as the diagonal sets do here. For grid work without backtracking, try Max Area of Island.

Rehearsing with Natively

The diagonal encoding is the part people forget under pressure, so it pays to explain it out loud a few times before the real thing. When you practice on a Mac or Windows PC, Natively can take a screenshot of the prompt, sketch the row-by-row search or the bitmask counter in Python, JavaScript or another language, and keep a transcript of your explanation for review. Details are on the AI interview assistant page.

Questions people ask

How do you solve N-Queens?

Place one queen per row with backtracking. For each row, try every column that is not already used and whose two diagonals are free, record the choice, recurse to the next row and undo it on return. A full set of n rows is one solution.

How do you check diagonals in O(1)?

Squares on the same down-right diagonal share the value row minus column, and squares on the same down-left diagonal share row plus column. Keep those values in two sets, or as bits in two integers, alongside a set of used columns.

What is the time complexity of N-Queens?

It is exponential. One queen per row and column gives fewer than n! complete placements to consider, and diagonal pruning removes most branches early. Building each returned board adds O(n²) per solution.

How many solutions does 8-Queens have?

92. Smaller boards are handy for testing: n = 4 has 2, n = 5 has 10, n = 6 has 4, and n = 2 and n = 3 have none.

Where to go next

Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.

Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.

Keep reading

Put it on your own machine.

A live-conversation assistant that runs locally. Your conversations stay on your machine.

macOS 12+ · Windows 10/11

© 2026 Natively AI Private Limited

Source-available under the Natively Personal Use Source License v1.0 · IP geolocation by DB-IP