TRT
Sign in
hardCoreLeetCode#backtracking#constraint sets

N-queens

Place n queens on an n × n board so that no two attack each other, and return every solution, pruning by column and diagonal.

The Runtime Theory Team1 min read
Taught inBacktracking basicsPro — members onlyBacktracking builds a solution one choice at a time, explores each choice recursively and undoes it afterwards. Pruning dead ends early is what makes it practical.
Solve it

Solving happens on the judge — come back and mark it done

Sample cases

inn = 4

out2 solutions

inn = 1

out[["Q"]]

inn = 8

out92 solutions

Return every way to place n queens on an n × n chessboard so that no two share a row, a column or a diagonal. Each solution is a board of Q and . strings.

Before you code

Place exactly one queen per row; then rows can never conflict. The search is over which column each row's queen takes, and the prune is to reject any column that is already attacked.

Hints

  1. Keep three sets: used columns, used diagonals (row - col) and used anti-diagonals (row + col).
  2. For each column in the current row, skip it if it is in any set; otherwise add it to all three, recurse to the next row, then remove it.
  3. When the row index reaches n, build the board from the chosen columns.
  4. For 8 queens, count how many placements your search tries. It should be in the tens of thousands, not billions.

Production & complexity notes

When solving N-queens on LeetCode (hard), always state your loop or recursion invariant before writing code. Verify how your chosen data structure behaves on degenerate inputs (single-element inputs, all-duplicate keys, strictly monotonic sequences, or maximum constraint sizes up to $10^5$ elements). In production interviews, pair your implementation with an explicit time and auxiliary space complexity proof, explain why alternative brute-force approaches violate the latency budget, and trace how cache locality and memory allocation overhead affect wall-clock throughput on real hardware. Review the step-by-step memory trace in Backtracking basics to reinforce the underlying pattern.

What it practices

The choose, explore, unchoose pattern and pruning, from Backtracking basics.

Not started

Sign in to save your learning progress.

Sign in to save