N-Queens (LeetCode 51): Solution and Explanation

Hard
Array
Backtracking

Place n queens on an n by n chessboard so that no two queens share a row, a column or a diagonal. Return every distinct arrangement, each drawn as a list of strings where 'Q' marks a queen and '.' marks an empty square.

Variables
No variables to display
DepthFunction Call
Stack empty
0/0

Intuition

The rawest brute force chooses n squares out of n² and checks each choice, which is astronomically large even for n = 8. A first improvement comes from the rules themselves: two queens can never share a row, so every valid board has exactly one queen per row. That turns the problem into choosing a column for each row, which is n to the power n possibilities, and since columns cannot repeat either, really n! permutations.

Backtracking shrinks that further by rejecting bad partial boards early. You fill the board one row at a time. For the current row you try each column, and before placing a queen you check whether it is attacked by any queen already placed above it. If it is safe, you place it and move to the next row; if the next rows dead-end, you remove it and try the next column. Whole subtrees of hopeless placements are never explored.

Because queens are only ever placed in rows above the current one, the safety check only needs to look upward: the same column, the upper-left diagonal and the upper-right diagonal. When the row index reaches n, every row has a safe queen, so you snapshot the board as strings and record it.

Approach: Row-by-row backtracking

  1. Build an n by n board filled with '.' and an empty result list.
  2. Write is_safe(row, col) that scans the column above, then walks up the upper-left diagonal, then the upper-right diagonal, returning False if it meets a 'Q'.
  3. Write backtrack(row). If row == n, join each board row into a string, append the list to result and return.
  4. Otherwise try every column. If is_safe(row, col) holds, set the square to 'Q' and call backtrack(row + 1).
  5. After the call returns, reset the square to '.' so the next column starts from a clean state.
  6. Call backtrack(0) and return result.

Step-by-step example

n = 4
  1. Row 0 tries column 0. Row 1 rejects columns 0 and 1 and places a queen at column 2.
  2. Row 2 finds every column attacked by (0,0) or (1,2), so it backtracks. Row 1 moves its queen to column 3, and row 2 places at column 1, but row 3 has no safe square. Column 0 in row 0 therefore leads nowhere.
  3. Row 0 tries column 1. Row 1 rejects columns 0, 1 and 2 and places at column 3.
  4. Row 2 places at column 0, which no earlier queen attacks, and row 3 places at column 2. The board with queens in columns 1, 3, 0 and 2 (top to bottom) is recorded.
  5. The search continues with row 0 at columns 2 and 3 and finds the mirror image with queens in columns 2, 0, 3 and 1, giving two solutions in total.

Code: Python, Java, C++

1class Solution:
2    def solveNQueens(self, n: int) -> List[List[str]]:
3        result = []
4        board = [['.' for _ in range(n)] for _ in range(n)]
5
6        def is_safe(row, col):
7            # Check column
8            for i in range(row):
9                if board[i][col] == 'Q':
10                    return False
11            # Check upper-left diagonal
12            i, j = row - 1, col - 1
13            while i >= 0 and j >= 0:
14                if board[i][j] == 'Q':
15                    return False
16                i -= 1
17                j -= 1
18            # Check upper-right diagonal
19            i, j = row - 1, col + 1
20            while i >= 0 and j < n:
21                if board[i][j] == 'Q':
22                    return False
23                i -= 1
24                j += 1
25            return True
26
27        def backtrack(row):
28            if row == n:
29                result.append([''.join(r) for r in board])
30                return
31            for col in range(n):
32                if is_safe(row, col):
33                    board[row][col] = 'Q'
34                    backtrack(row + 1)
35                    board[row][col] = '.'
36
37        backtrack(0)
38        return result

Time and space complexity

Time

O(n! × n)

With one queen per row and no column reused, the search explores at most about n! partial placements, and each candidate square costs O(n) in is_safe to scan its column and two diagonals. Recording a solution adds O(n²) to build its strings.

Space

O(n²)

The board takes n² cells, and the recursion is at most n levels deep. The output itself is not counted.

Other approaches

Backtracking with column and diagonal sets (time O(n!), space O(n²))

Track used columns, used row - col diagonals and used row + col anti-diagonals in three sets. The safety check becomes O(1), so the search keeps the same tree but does less work per node.

Bitmask backtracking (time O(n!), space O(n))

Represent occupied columns and diagonals as integers and compute all free columns for a row with one bitwise expression. It is the fastest practical approach for counting solutions and works well up to n around 15.

Common mistakes

  • Checking the full row or the lower diagonals. Only rows above are filled, so checking below is wasted work, and checking the current row is unnecessary because you place one queen per row.
  • Forgetting to reset the square to '.' after the recursive call, which leaves stray queens that make later checks reject valid squares.
  • Appending the board itself rather than a fresh list of strings. Later backtracking mutates the board, so stored results would change.
  • Mixing up the diagonal walks. The upper-left walk decrements both indices, and the upper-right walk decrements the row while incrementing the column.

Frequently asked questions

How many solutions does N-Queens have?

For n = 1 there is one, n = 2 and n = 3 have none, n = 4 has two, n = 8 has 92, and n = 9 has 352. There is no simple closed formula, which is why the problem is solved by search.

What is the time complexity of N-Queens backtracking?

It is usually stated as O(n!) placements, because each row has fewer usable columns than the one above. With the O(n) safety scan used here, it is O(n! × n), which is easily fast enough for n up to 9.

How do you check diagonals quickly?

Squares on the same diagonal share row - col, and squares on the same anti-diagonal share row + col. Storing those values in sets lets you test a square in constant time instead of walking the board.

What is the difference between N-Queens and N-Queens II?

The first asks for every board layout, and the second only asks how many layouts exist. The search is identical, but the second version can skip building strings and just increment a counter.