LeetCode #51 Hard

N-Queens

N-Queens is LeetCode 51 (Hard). Place n queens on an n × n chessboard so that no two queens attack each other: no two may share a row, a column or a diagonal.

  • Return every valid board.
  • Each board is a list of n strings, with 'Q' for a queen and '.' for an empty square.

The classic 8 queens problem is the case n = 8. With n at most 9 the number of boards stays small, but trying every placement of n queens on n² squares does not, so the search must cut off bad branches early.

Constraints
  • 1 <= n <= 9
backtracking
Open on LeetCode ↗
02

Intuition

Since no two queens can share a row, every valid board has exactly one queen in each row. So build the board row by row: in each row, try each column, and go on to the next row only if that square is safe.

  • Fast safety check: squares on one down-right diagonal share the same row − col, and squares on one up-right diagonal share the same row + col. Three sets (columns, row − col values, row + col values) answer "is this square attacked?" in O(1).
  • Backtracking: when a row has no safe square, the queen above it is in a bad spot. Remove it, un-mark its lines, and try that row's next column.

Reaching row n means every row holds a safe queen, so the board is saved.

How to spot this pattern

Build an arrangement one choice at a time, where each choice rules out later ones and all valid arrangements are wanted: that is backtracking. Sudoku Solver and Permutations follow the same place, recurse, undo rhythm.

03

Approach

Try it first

Before reading on, write the row − col and row + col values on a 4 × 4 grid and check that each diagonal shares one value. Aim for a search that never places two queens in one row.

1

Fill one row per call

Write place(row), which puts a queen somewhere in row and then calls place(row + 1). Choosing one square per row makes row clashes impossible, so only columns and diagonals need checking.

2

Skip attacked squares

For each col in the row, skip it if col is in the column set, row − col is in the down-diagonal set, or row + col is in the up-diagonal set. Any of those means an earlier queen already covers that square.

3

Place, recurse, then undo

On a safe square, add its three values to the sets, write 'Q' into the grid, and call place(row + 1). When the call returns, remove the three values and reset the square to '.', so the next column starts from the same board.

4

Save a copy at row n

When row == n, all rows hold a queen that no other queen attacks. Turn each grid row into a string and append the copy to the answer, because the grid itself keeps changing.

04

Code in Python, C++ and Java

▶1class Solution:
▶2 def solveNQueens(self, n):
▶3 boards = []
▶4 grid = [["."] * n for _ in range(n)]
▶5 cols, downs, ups = set(), set(), set()
▶6 
▶7 def place(row):
▶8 if row == n:
▶9 boards.append(["".join(r) for r in grid])
▶10 return
▶11 for col in range(n):
▶12 if col in cols or row - col in downs or row + col in ups:
▶13 continue
▶14 cols.add(col)
▶15 downs.add(row - col)
▶16 ups.add(row + col)
▶17 grid[row][col] = "Q"
▶18 place(row + 1)
▶19 cols.remove(col)
▶20 downs.remove(row - col)
▶21 ups.remove(row + col)
▶22 grid[row][col] = "."
▶23 
▶24 place(0)
▶25 return boards
boardcolumns takenrow − col takenrow + col takenempty 4 × 4 board → start at row 0
n4
Each row must hold exactly one queen, so the search fills the board one row at a time, trying columns left to right. Nothing is taken yet.
boardQcolumns taken0row − col taken0row + col taken0row 0: queen at column 0
row, col0, 0
cols0
downs0
ups0
Column 0 is free on all three counts, so a queen goes here and its column, its row − col value 0 and its row + col value 0 are marked as taken.
boardQ✕✕Qcolumns taken02row − col taken-10row + col taken03row 1: columns 0, 1 attacked → queen at column 2
row, col1, 2
cols0, 2
downs0, -1
ups0, 3
Skipped because (1, 0) is on column 0; (1, 1) is on the row − col 0 diagonal. Column 2 is free on all three counts, so a queen goes here and its column, its row − col value -1 and its row + col value 3 are marked as taken.
boardQQ✕✕✕✕columns taken02row − col taken-10row + col taken03row 2: no free column left → back up
row2
Every remaining square is attacked: (2, 0) is on column 0; (2, 1) is on the row + col 3 diagonal; (2, 2) is on column 2 and the row − col 0 diagonal; (2, 3) is on the row − col -1 diagonal. No queen fits in row 2, so the queen in row 1 must move.
boardQcolumns taken0row − col taken0row + col taken0take back the queen at row 1, column 2
row, col1, 2
cols0
Everything below this queen has been tried. Removing it and un-marking its column and diagonals restores the board exactly as it was, so row 1 can try its next column.
boardQQcolumns taken03row − col taken-20row + col taken04row 1: queen at column 3
row, col1, 3
cols0, 3
downs0, -2
ups0, 4
Column 3 is free on all three counts, so a queen goes here and its column, its row − col value -2 and its row + col value 4 are marked as taken.
boardQQ✕Qcolumns taken013row − col taken-201row + col taken034row 2: column 0 attacked → queen at column 1
row, col2, 1
cols0, 3, 1
downs0, -2, 1
ups0, 4, 3
Skipped because (2, 0) is on column 0. Column 1 is free on all three counts, so a queen goes here and its column, its row − col value 1 and its row + col value 3 are marked as taken.
boardQQQ✕✕✕✕columns taken013row − col taken-201row + col taken034row 3: no free column left → back up
row3
Every remaining square is attacked: (3, 0) is on column 0 and the row + col 3 diagonal; (3, 1) is on column 1 and the row + col 4 diagonal; (3, 2) is on the row − col 1 diagonal; (3, 3) is on column 3 and the row − col 0 diagonal. No queen fits in row 3, so the queen in row 2 must move.
boardQQcolumns taken03row − col taken-20row + col taken04take back the queen at row 2, column 1
row, col2, 1
cols0, 3
Everything below this queen has been tried. Removing it and un-marking its column and diagonals restores the board exactly as it was, so row 2 can try its next column.
boardQQ✕✕columns taken03row − col taken-20row + col taken04row 2: no free column left → back up
row2
Every remaining square is attacked: (2, 2) is on the row − col 0 diagonal and the row + col 4 diagonal; (2, 3) is on column 3. No queen fits in row 2, so the queen in row 1 must move.
boardQcolumns taken0row − col taken0row + col taken0take back the queen at row 1, column 3
row, col1, 3
cols0
Everything below this queen has been tried. Removing it and un-marking its column and diagonals restores the board exactly as it was, so row 1 can try its next column.
boardQcolumns taken0row − col taken0row + col taken0row 1: no free column left → back up
row1
Row 1 has no columns left to try. No queen fits in row 1, so the queen in row 0 must move.
boardcolumns takenrow − col takenrow + col takentake back the queen at row 0, column 0
row, col0, 0
colsnone
Everything below this queen has been tried. Removing it and un-marking its column and diagonals restores the board exactly as it was, so row 0 can try its next column.
boardQcolumns taken1row − col taken-1row + col taken1row 0: queen at column 1
row, col0, 1
cols1
downs-1
ups1
Column 1 is free on all three counts, so a queen goes here and its column, its row − col value -1 and its row + col value 1 are marked as taken.
boardQ✕✕✕Qcolumns taken13row − col taken-2-1row + col taken14row 1: columns 0, 1, 2 attacked → queen at column 3
row, col1, 3
cols1, 3
downs-1, -2
ups1, 4
Skipped because (1, 0) is on the row + col 1 diagonal; (1, 1) is on column 1; (1, 2) is on the row − col -1 diagonal. Column 3 is free on all three counts, so a queen goes here and its column, its row − col value -2 and its row + col value 4 are marked as taken.
boardQQQcolumns taken013row − col taken-2-12row + col taken124row 2: queen at column 0
row, col2, 0
cols1, 3, 0
downs-1, -2, 2
ups1, 4, 2
Column 0 is free on all three counts, so a queen goes here and its column, its row − col value 2 and its row + col value 2 are marked as taken.
boardQQQ✕✕Qcolumns taken0123row − col taken-2-112row + col taken1245row 3: columns 0, 1 attacked → queen at column 2
row, col3, 2
cols1, 3, 0, 2
downs-1, -2, 2, 1
ups1, 4, 2, 5
Skipped because (3, 0) is on column 0; (3, 1) is on column 1 and the row − col 2 diagonal and the row + col 4 diagonal. Column 2 is free on all three counts, so a queen goes here and its column, its row − col value 1 and its row + col value 5 are marked as taken.
boardQQQQcolumns taken0123row − col taken-2-112row + col taken1245all 4 rows filled → save board 1
boards1
Every row has a queen and no two share a column or diagonal, so this board is a valid answer and gets copied into the result. The search then backs up to look for more.
boardQQQQcolumns taken0123row − col taken-2-112row + col taken1245its mirror image also works → 2 boards in total
boards2
The search keeps backing up and trying later columns in exactly the same way. For n = 4 it finds 2 boards in all; flipping a board left to right always gives another valid one, like the board shown here.
05

Common pitfalls

Indexing an array with row − col

✗ Wrong
downs = [False] * n
if downs[row - col]: ...
✓ Right
downs = [False] * (2 * n - 1)
if downs[row - col + n - 1]: ...

row − col runs from −(n − 1) to n − 1, which is 2n − 1 values. In C++ or Java a negative index crashes or reads the wrong memory; in Python downs[-1] silently reads the last slot, so for n = 4 the square (0, 1) and the square (3, 0) share a flag and valid boards get rejected. Shift by n − 1 and size the array 2n − 1.

Building the grid with list multiplication

✗ Wrong
grid = [["."] * n] * n
✓ Right
grid = [["."] * n for _ in range(n)]

The outer * n repeats one inner list n times. Writing a queen into row 0 writes it into every row, so for n = 4 the saved boards contain columns full of 'Q'.

Saving the grid instead of a copy

✗ Wrong
boards.append(grid)
✓ Right
boards.append(["".join(r) for r in grid])

Every saved entry points at the same grid, which the undo step wipes back to dots. For n = 4 the result holds two all-dot boards instead of the two solutions.

06

Edge cases

n = 2 or n = 3

No arrangement works, and the search returns an empty list after trying every first-row column.

n = 1

One queen on one square is valid, so the answer is [["Q"]].

07

Complexity

Time
O(n!)
Space
O(n²)
Row 0 has n choices, row 1 at most n − 1 safe columns, and so on, so the search tree has at most about n! leaves; each check is O(1) and copying a board costs O(n²). The grid takes O(n²) space, the sets and the call stack O(n), not counting the returned boards.
08

N-Queens FAQ

How many solutions does the 8 queens problem have?

92 boards. Many are rotations or mirror images of each other; grouping those together leaves 12 truly different solutions. For n from 1 to 9 the counts are 1, 0, 0, 2, 10, 4, 40, 92 and 352.

What if I only need the number of boards?

That is N-Queens II (LeetCode 52). Use the same search but add 1 at row == n instead of building strings. Replacing the three sets with bitmasks of taken columns and diagonals makes it faster still.

Is there a way to place n queens without searching?

Yes, for a single board. Explicit patterns exist for every n ≥ 4 (for example, rules based on n mod 6 that list the column for each row). They give one valid board in O(n), but not all of them, so this problem still needs backtracking.