Coding interview problems › Backtracking

🧩 Backtracking Hard

N-Queens

N-Queens explained: place queens row by row with backtracking and O(1) column and diagonal checks, tested Python returning every board, with a live visual.

Also searched as: N queens problem backtracking Ā· 8 queens problem Ā· place n queens so none attack

šŸ‘‘

Try it live Free

N-Queens & Backtracking

Place queens column by column, watch them get attacked, back up and lock into a safe board; this solution does the same thing row by row.

Also useful: Backtracking: Subsets, Permutations & Pruning

Open the playground →

The problem

Place n queens on an n Ɨ n chessboard so that no two queens attack each other (no two share a row, column or diagonal). Return every distinct solution, each drawn as a list of strings with Q for a queen and . for an empty square.

Inputn = 4
Output[[".Q..", "...Q", "Q...", "..Q."], ["..Q.", "Q...", "...Q", ".Q.."]]
Inputn = 1
Output[["Q"]]

The key insight

Every row must hold exactly one queen, so place them one row at a time. For each row try each column, but only if that column and both diagonals are free. Cells on the same "\" diagonal share row - col; cells on the same "/" diagonal share row + col. Three sets make each safety check O(1), and a dead end immediately undoes the last queen.

Brute force first: Trying every placement of n queens among n² squares (or even all nn one-per-row placements) and checking each board is hopeless beyond tiny n.

Step-by-step approach

  1. Keep sets cols, diag (row - col) and anti (row + col), plus queens, the column chosen in each row.
  2. Define dfs(row): if row == n, convert queens into a board and record it.
  3. For each column c, skip it if c, row - c or row + c is already taken.
  4. Otherwise add all three, append c, recurse on row + 1, then remove them (backtrack).
  5. Call dfs(0).

Python solution

PYTHON 3tested
def solve_n_queens(n):
    out, queens = [], []                    # queens[r] = column in row r
    cols, diag, anti = set(), set(), set()

    def dfs(row):
        if row == n:
            out.append(["." * c + "Q" + "." * (n - c - 1) for c in queens])
            return
        for c in range(n):
            if c in cols or row - c in diag or row + c in anti:
                continue                    # attacked: prune
            cols.add(c); diag.add(row - c); anti.add(row + c)
            queens.append(c)
            dfs(row + 1)
            queens.pop()
            cols.remove(c); diag.remove(row - c); anti.remove(row + c)

    dfs(0)
    return out

Complexity

TimeO(n!)
SpaceO(n)

Row r has at most n - r free columns, so the search is bounded by n!, and pruning on diagonals makes it far smaller. The sets and recursion hold O(n) entries (plus O(n²) per stored board).

Common mistakes

Frequently asked questions

What is the time and space complexity of N-Queens?

The search is bounded by O(n!) because each row has fewer free columns than the last, and pruning makes it much faster in practice. Extra space is O(n) for the sets and recursion, plus the output boards.

How many solutions does N-Queens have?

For n = 1 to 8: 1, 0, 0, 2, 10, 4, 40, 92. The classic 8-queens puzzle has 92 solutions.

How do I just count the solutions (N-Queens II)?

Use the same backtracking and increment a counter at row == n instead of building boards. Bitmasks for columns and diagonals make it even faster.

Why do cells on a diagonal share row - col?

Moving one step down-right adds 1 to both row and column, so their difference stays constant. Moving down-left adds 1 to row and subtracts 1 from column, so their sum stays constant.

Preparing for placements?

Take the 2-minute readiness check to find your weak patterns, then follow the placement path from DSA core to system design.

All coding interview problems More Backtracking Backtracking: Subsets, Permutations & Pruning lab Placement prep guides

Problem statements on this site are written in our own words. Problem names are the common names used across interview-prep communities; BitBootcamp is an independent learning platform and is not affiliated with LeetCode or any company that asks these questions.