Skip to content
Work Practice Products Coding interviews Machine learning coding Quant developer HFT course Blog Method Why me About Book a call

Coding · Backtracking

Counting n-queens placements

Hard · Target 25 minutes · Backtracking· Type asked at

Place n queens on an n × n chessboard so that no two attack each other: no two share a row, a column or a diagonal. Return the number of distinct placements.

Examples

InputOutputWhy
n = 42Columns by row: 2, 4, 1, 3 and its mirror 3, 1, 4, 2.
n = 11One queen on one square.
n = 30No placement exists for n = 2 or n = 3.

Constraints

  • 1 ≤ n ≤ 12

Hints

Hint 1

Two queens in one row always attack each other, so each row holds exactly one queen. What does that reduce the problem to?

Hint 2

Place queens row by row. For the current row, which columns are still safe given the queens above?

Hint 3

Keep three sets: columns in use, "\" diagonals in use (row − column constant) and "/" diagonals in use (row + column constant). A square is safe if it is in none of them.

Where people lose marks

  • Checking attacks by scanning the whole board for every candidate square: correct but O(n²) per check.
  • Forgetting one diagonal direction. Both r − c and r + c must be tracked.
  • With arrays for diagonals, indexing r − c without an offset: it goes negative. Add n − 1.
  • In the bitmask version, not masking with (1 << n) − 1: bits shifted past column n − 1 are treated as columns.
Console⌘/Ctrl + Enter runs

Write a solution and run it against the real test table.


Keep going

Preparing for a real process? Quant interview preparation, or book a free 20-minute call.