Taro Logo

N-Queens II

#2 Most AskedHard
0 views
Topics:
ArraysRecursionBacktracking

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 the number of distinct solutions to the n-queens puzzle.

Example 1:

Input: n = 4
Output: 2
Explanation: There are two distinct solutions to the 4-queens puzzle as shown.

Example 2:

Input: n = 1
Output: 1

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 possible value of `n`? Are there any constraints on the size of the board?
  2. Is 'distinct solutions' defined as unique board configurations, or are rotations/reflections of the same configuration considered distinct?
  3. If n is 0, should I return 1 (representing an empty board as a solution) or 0 (representing no possible placement)?
  4. Can I assume that the input `n` will always be a non-negative integer?
  5. Could you provide a small example (e.g., n=3 or n=4) and the corresponding expected output to clarify the problem further?

Brute Force Solution

Approach

Imagine placing game pieces on a grid where no two pieces can threaten each other horizontally, vertically, or diagonally. The brute force approach systematically tries placing the pieces on every possible square of the grid to test all potential arrangements.

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

  1. Begin by placing the first game piece in the top row, trying every single square in that row one by one.
  2. For each choice in the first row, move to the second row and try placing the next game piece on every available square.
  3. Continue this process row by row, testing every possible combination of positions from top to bottom.
  4. Whenever a placement creates a conflict where pieces threaten one another, immediately abandon that entire path and try the next available spot.
  5. Whenever you successfully place all the pieces on the grid without any conflicts, count that arrangement as a valid solution.
  6. Keep a running total of every successful arrangement you discover along the way.
  7. Once every single combination of piece placements has been thoroughly tested and checked, your running total will give you the final answer.

Code Implementation

class Solution:
    def totalNQueens(self, board_size: int) -> int:
        def backtrack_queens(row_index, columns, diagonals_main, diagonals_anti):
            if row_index == board_size:
                return 1

            # We prune invalid branches early to avoid exploring useless configurations
            valid_solutions_count = 0
            for column_index in range(board_size):
                main_diagonal_key = row_index - column_index
                anti_diagonal_key = row_index + column_index

                if column_index in columns or main_diagonal_key in diagonals_main or anti_diagonal_key in diagonals_anti:
                    continue

                columns.add(column_index)
                diagonals_main.add(main_diagonal_key)
                diagonals_anti.add(anti_diagonal_key)

                valid_solutions_count += backtrack_queens(row_index + 1, columns, diagonals_main, diagonals_anti)

                columns.remove(column_index)
                diagonals_main.remove(main_diagonal_key)
                diagonals_anti.remove(anti_diagonal_key)

            return valid_solutions_count

        # We initialize the tracking sets to maintain state across recursive depth
        active_columns = set()
        active_main_diagonals = set()
        active_anti_diagonals = set()

        return backtrack_queens(0, active_columns, active_main_diagonals, active_anti_diagonals)

Big(O) Analysis

Time Complexity
O(n!) – To determine the time complexity, we examine the recursive backtracking process across the n rows of the board. In the first row we have n choices, in the second row slightly fewer valid choices due to conflicts, and roughly (n-2) for the third, continuing this constrained factorial reduction down to the last row. This exhaustive exploration of non-attacking placements results in a maximum of approximately n factorial operations in the worst-case scenario. When simplified, this bounding behavior gives us a final Big O runtime of O(n!).
Space Complexity
O(N) – The auxiliary space is primarily determined by the recursion stack, which reaches a maximum depth of N corresponding to one queen placed per row. Additionally, we use three tracking sets or bitmasks of size proportional to N to keep track of occupied columns and diagonals and prevent conflicts. Since N represents both the maximum depth of recursive calls and the size of the position tracking structures, the total extra memory scales linearly. Therefore, simplifying these components to Big O notation yields O(N).

Optimal Solution

Approach

Instead of checking every single possible square on the board, the optimal strategy builds the solution row by row. It uses a clever tracking system to instantly spot which diagonal paths and columns are blocked, avoiding dead ends before they happen.

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

  1. Begin at the very top row of the board and look for an empty spot to place a game piece.
  2. Before placing the piece, check if the chosen spot is already being watched or threatened by another piece placed in a previous row, both vertically and diagonally.
  3. If the spot is safe, place the piece and immediately mark that specific column and diagonal paths as blocked so no other piece can use them.
  4. Move down to the next row and repeat the search for a safe spot.
  5. If you ever reach a row where every single spot is blocked, step back to the previous row, move the piece to a different safe spot, and continue forward.
  6. Keep track of every time you successfully place a piece on the final bottom row, as this represents a complete and valid winning arrangement.
  7. Once all possibilities have been explored and adjusted, count up the total number of successful arrangements found.

Code Implementation

class Solution:
    def totalNQueens(self, board_size: int) -> int:
        total_solutions_found = 0
        columns_set = set()
        positive_diagonals_set = set()
        negative_diagonals_set = set()

        def backtrack(current_row_index):
            nonlocal total_solutions_found

            # Reaching beyond the final row means a valid configuration was successfully completed.
            if current_row_index == board_size:
                total_solutions_found += 1
                return

            for current_column_index in range(board_size):
                positive_diagonal_index = current_row_index + current_column_index
                negative_diagonal_index = current_row_index - current_column_index

                # Skip placements that violate existing diagonal or vertical constraints.
                if (current_column_index in columns_set or 
                    positive_diagonal_index in positive_diagonals_set or 
                    negative_diagonal_index in negative_diagonals_set):
                    continue

                columns_set.add(current_column_index)
                positive_diagonals_set.add(positive_diagonal_index)
                negative_diagonals_set.add(negative_diagonal_index)

                backtrack(current_row_index + 1)

                # Undo the placement to explore alternative configurations for previous rows.
                columns_set.remove(current_column_index)
                positive_diagonals_set.remove(positive_diagonal_index)
                negative_diagonals_set.remove(negative_diagonal_index)

        backtrack(0)

        return total_solutions_found

Big(O) Analysis

Time Complexity
O(n!) – The algorithm uses recursive backtracking to place queens row by row on an n by n board, exploring up to n choices for the first row, n-1 for the second, and so on. The tracking system allows constant time checks for columns and diagonals, but the recursion tree still branches across these decreasing permutations. This total exploration approximates n multiplied by (n-1) multiplied by (n-2) down to 1 operations, which simplifies to the factorial time complexity of O(n!).
Space Complexity
O(N) – The auxiliary space is driven by the recursion stack that reaches a maximum depth of N as we place one queen per row down the board. Additionally, we use three tracking structures: a column set of size N, a primary diagonal set of size up to 2N, and an anti-diagonal set of size up to 2N. Combining the depth of the recursive calls and the constant number of tracking sets for a board of size N, the total extra memory simplifies in Big O notation to O(N).

Edge Cases

n equals 1
How to Handle:
The backtracking algorithm should immediately place the queen at row 0 column 0 and return 1.
n equals 2 or 3
How to Handle:
The algorithm explores all combinations and correctly yields 0 as no valid placements exist.
n equals 4
How to Handle:
The classic smallest non-trivial board size should correctly return 2 distinct solutions.
n equals 9, the upper constraint limit
How to Handle:
An optimized backtracking solution using bit manipulation processes this within the time limit without TLE.
Zero or negative n values
How to Handle:
Input validation should return 0 since a chessboard cannot have a non-positive dimension.
Large recursion depth leading to stack overflow
How to Handle:
Since n is capped at 9 in standard constraints, the call stack depth remains safely within system limits.
Bitwise operations overflow in Java or C++
How to Handle:
Using standard integer or long types is sufficient since 9 bits easily fit within 32-bit and 64-bit integers.
Symmetric solutions being double counted
How to Handle:
Row-by-row recursive placement naturally generates unique configurations by fixing one queen per row.
0/4 completed