N-Queens
Description:
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"]]
Video Explanation

Approaches:
1. Backtracking
The most effective way to solve the N-Queens problem is using Backtracking. We place queens row by row. For each row, we try to place a queen in each column. We must ensure that the new queen is not under attack by any previously placed queens.
- Maintain three sets to track the columns and the two diagonals (positive and negative) that are currently occupied by queens.
- The positive diagonal has a constant property where
row + colis the same for all elements on that diagonal. - The negative diagonal has a constant property where
row - colis the same for all elements on that diagonal. - Create a recursive
backtrackfunction that starts atrow = 0. - If
row == n, a valid board configuration has been found, so we format it and add it to our results. - For the current row, iterate through each column
c. If placing a queen at(row, c)violates any of our sets, skip it. - Otherwise, place the queen, update the sets, and recursively call
backtrack(row + 1). - After exploring that path, remove the queen and back out of the sets to explore other possibilities.
- Time Complexity: where is the number of queens. For the first row we have choices, for the next roughly , and so on, leading to a factorial time complexity.
- Space Complexity: for storing the board state and the output array, plus for the recursion stack and the sets used to track attacks.