Taro Logo

N-Queens

#209 Most AskedHard
Topics:
Recursion

The n-queens puzzle is the problem of placing n queens on an n x n chessboard such that no two queens attack each other.

Given an integer n, return all distinct solutions to the n-queens puzzle. You may return the answer in any order.

Each solution contains a distinct board configuration of the n-queens' placement, where 'Q' and '.' both indicate a queen and an empty space, respectively.

Example 1:

Input: n = 4
Output: [[".Q..","...Q","Q...","..Q."],["..Q.","Q...","...Q",".Q.."]]
Explanation: There exist two distinct solutions to the 4-queens puzzle as shown above

Example 2:

Input: n = 1
Output: [["Q"]]

Constraints:

  • 1 <= n <= 9

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. What is the maximum value of $n$ we can expect for the chessboard size?
  2. What is the exact expected output format for each solution (e.g., a list of strings where 'Q' represents a queen and '.' represents an empty space, or a list of integer column indices for each row)?
  3. If there are no valid configurations for a given $n$, should we return an empty list or something else?
  4. Is there any specific ordering required for the returned list of distinct solutions?
  5. Should we consider rotated or mirrored board configurations as duplicate solutions, or are all geometrically distinct valid placements required?

Brute Force Solution

Approach

Imagine you need to place a specific number of queens on a game board of the same size so that no queen can attack any other. The brute force approach involves testing every single possible way to place the queens on the board and checking each layout to see if it is safe.

Here's how the algorithm would work step-by-step:

  1. Begin by placing the first queen in the very first available spot on the top row.
  2. Move to the next row and place the second queen in the first available spot.
  3. Continue this process, placing one queen on each consecutive row until you have placed a queen on every row of the board.
  4. Once you have a complete layout with all queens placed, inspect the entire board to see if any queen is threatening another horizontally, vertically, or diagonally.
  5. If you find that any queen can attack another, reject this layout and try moving the last queen to the next available spot in that row.
  6. If you run out of spots in the current row, move the previous row's queen to its next available spot and start placing the subsequent queens again.
  7. If a layout is completely safe and no queen threatens another, save this arrangement as a successful solution.
  8. Repeat this exhaustive trial-and-error process for every imaginable combination until you have explored all possible placements on the board.

Code Implementation

class Solution:
    def solveNQueens(self, board_size: int):
        all_solutions = []
        current_board = [-1] * board_size

        def is_layout_safe(queen_positions):
            row_index = len(queen_positions) - 1
            for previous_row in range(row_index):
                column_difference = abs(queen_positions[previous_row] - queen_positions[row_index])
                row_difference = row_index - previous_row
                if column_difference == 0 or column_difference == row_difference:
                    return False
            return True

        def explore_combinations(current_row):
            if current_row == board_size:
                formatted_solution = []
                for queen_column in current_board:
                    formatted_solution.append("." * queen_column + "Q" + "." * (board_size - 1 - queen_column))
                all_solutions.append(formatted_solution)
                return

            # We must test every column position in the current row to find all possible placements
            for column_index in range(board_size):
                current_board[current_row] = column_index

                # We check the layout safety early to prune invalid subtrees and avoid wasted work
                if is_layout_safe(current_board[:current_row + 1]):
                    explore_combinations(current_row + 1)

            current_board[current_row] = -1

        explore_combinations(0)
        return all_solutions

Big(O) Analysis

Time Complexity
O(n!) – The cost is driven by the recursive backtracking process of placing one queen per row across n rows. On the first row we have n choices, on the second row fewer valid choices due to conflicts, and roughly n times (n-1) times (n-2) down to 1 choices for the complete board configurations. This exhaustive trial-and-error exploration of permutations approximates n factorial operations, which simplifies to O(n!).
Space Complexity
O(N) – The auxiliary space complexity is driven by the recursive call stack and tracking structures that store the queens' positions row by row. Since we place exactly one queen per row, the maximum depth of the recursion stack reaches N. Additionally, the tracking sets or arrays used to check column and diagonal attacks require space proportional to N. Therefore, the total extra memory scales linearly with the input board dimension N.

Optimal Solution

Approach

Instead of blindly testing every possible position for every game piece on the entire board, we place pieces row by row and immediately abandon any path the moment a piece threatens another. This smart shortcut prevents us from wasting time exploring dead ends that violate the safety rules.

Here's how the algorithm would work step-by-step:

  1. Begin at the top row of the board and prepare to place your first piece.
  2. Look at the available spots in the current row and choose one that is completely safe from any pieces placed higher up on the board.
  3. Once you place a piece, immediately mark the column and both diagonal paths below it as off-limits so future pieces cannot cross them.
  4. Move down to the next row and repeat the process of placing a piece in a safe spot.
  5. If you ever reach a row where every single spot is blocked by a previous piece, recognize that your current arrangement has a conflict.
  6. Step back up to the previous row, gently remove the last piece you placed, and try shifting it to a different safe spot.
  7. Continue this process of moving forward when successful and stepping backward when stuck until you successfully place a piece on the bottom row.
  8. Whenever you complete a full board, record that successful layout and continue exploring to find every other possible arrangement.

Code Implementation

class Solution:
    def solveNQueens(self, board_dimension: int) -> list[list[str]]:
        all_valid_solutions = []
        
        occupied_columns = set()
        positive_diagonals = set()
        negative_diagonals = set()
        current_board_state = []

        def backtrack_rows(current_row):
            if current_row == board_dimension:
                formatted_board = []
                for row_index in current_board_state:
                    formatted_board.append("." * row_index + "Q" + "." * (board_dimension - row_index - 1))
                all_valid_solutions.append(formatted_board)
                return

            for column_index in range(board_dimension):
                # We prune branches instantly when a queen threatens another via columns or diagonals.
                if (column_index in occupied_columns or 
                    (current_row - column_index) in positive_diagonals or 
                    (current_row + column_index) in negative_diagonals):
                    continue

                occupied_columns.add(column_index)
                positive_diagonals.add(current_row - column_index)
                negative_diagonals.add(current_row + column_index)
                current_board_state.append(column_index)

                backtrack_rows(current_row + 1)

                # Backtracking allows us to undo our previous placement and explore alternative safe spots.
                current_board_state.pop()
                negative_diagonals.remove(current_row + column_index)
                positive_diagonals.remove(current_row - column_index)
                occupied_columns.remove(column_index)

        backtrack_rows(0)
        return all_valid_solutions

Big(O) Analysis

Time Complexity
O(n!) – In the worst-case scenario, the algorithm tries n choices for the first row, n minus 2 choices for the second row since columns and diagonals are blocked, and roughly n minus 4 choices for the subsequent rows. This recursive backtracking explores a rapidly narrowing branching factor across n levels of the board. The total operations approximate the product n times n minus 1 times n minus 2 down to 1, which represents the factorial growth rate. Therefore, the time complexity simplifies to O(n!).
Space Complexity
O(N) – The algorithm requires auxiliary space for the recursion stack, which reaches a maximum depth of N as we place pieces row by row from top to bottom. Additionally, we use tracking structures such as arrays or sets of size N to mark off-limits columns and diagonals as described in step 3. The output list storing all valid board layouts grows depending on the number of solutions, but the auxiliary memory driven by the recursion and tracking constraints scales linearly with the board dimension N. Therefore, the total extra memory simplifies in Big O notation to O(N) auxiliary space, excluding the final output storage.

Edge Cases

Input n equals 1
How to Handle:
The backtracking algorithm immediately places the single queen at position zero and returns the single valid board configuration.
Input n equals 2 or 3
How to Handle:
The recursive exploration will exhaust all possibilities and correctly return an empty list because no valid non-attacking configuration exists for these sizes.
Maximum standard constraint where n equals 9
How to Handle:
The backtracking approach scales efficiently within time limits by pruning invalid branches early via diagonal and column tracking sets.
Zero or negative values for n
How to Handle:
The problem constraints typically define n as a positive integer at least 1, but input validation should immediately return an empty list.
Deep recursion stack for larger n values up to 9
How to Handle:
The maximum recursion depth is bounded by n, which safely avoids stack overflow errors in standard runtime environments.
Multiple valid solutions exist for larger n such as n equals 8
How to Handle:
The algorithm uses a global or passed accumulator list to collect every distinct valid board configuration during the backtracking traversal.
Symmetric solutions generated during board traversal
How to Handle:
The standard backtracking algorithm treats mirrored or rotated configurations as distinct solutions as required by the problem statement.
Memory limits due to large output size for larger boards
How to Handle:
String formatting is performed only upon finding a complete valid configuration to minimize intermediate memory overhead.
0/245 completed