N Queens Problem in DSA Javascript - Time & Space Complexity
We want to understand how the time needed to solve the N Queens problem grows as we increase the board size.
Specifically, how does the number of steps change when we try to place queens on larger chessboards?
Analyze the time complexity of the following code snippet.
function solveNQueens(board, row) {
if (row === board.length) return true;
for (let col = 0; col < board.length; col++) {
if (isSafe(board, row, col)) {
board[row][col] = 'Q';
if (solveNQueens(board, row + 1)) return true;
board[row][col] = '.'; // backtrack
}
}
return false;
}
This code tries to place queens row by row, checking safe positions and backtracking if needed.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The for-loop tries all columns in a row, and recursion explores all rows.
- How many times: Up to N columns per row, repeated for each of the N rows, with backtracking exploring many combinations.
As the board size (n) grows, the number of ways to place queens grows very fast because we try many column choices for each row and backtrack often.
| Input Size (n) | Approx. Operations |
|---|---|
| 4 | Few hundred tries |
| 8 | Thousands of tries |
| 12 | Millions of tries |
Pattern observation: The operations grow very quickly, much faster than just doubling or squaring.
Time Complexity: O(N!)
This means the time needed grows roughly like the factorial of the board size, which is very fast growth.
[X] Wrong: "The time grows like N squared because we have two loops."
[OK] Correct: The recursion and backtracking cause many more combinations to check, making the growth much faster than just two loops.
Understanding this problem's time complexity helps you explain how backtracking explores many possibilities and why some problems become very slow as input grows.
"What if we used a heuristic to skip some columns early? How would that affect the time complexity?"
Practice
N Queens Problem in chess?Solution
Step 1: Understand the problem objective
The N Queens Problem requires placing queens so that none can attack another. Queens attack horizontally, vertically, and diagonally.Step 2: Analyze the options
Only Place N queens on an NxN board so no two queens attack each other correctly states the goal: no two queens attack each other on an NxN board.Final Answer:
Place N queens on an NxN board so no two queens attack each other -> Option AQuick Check:
Goal = safe queen placement [OK]
- Thinking queens can share rows or columns
- Ignoring diagonal attacks
- Confusing attack with placement
Solution
Step 1: Understand recursive approach parameters
Typically, the recursive function takes the board state and the current row to place a queen.Step 2: Check options for correct parameters
function solveNQueens(board, row) {} usesboardandrow, which fits the common recursive pattern.Final Answer:
function solveNQueens(board, row) {} -> Option AQuick Check:
Recursive function = board + current row [OK]
- Using column instead of row for recursion
- Missing board parameter
- Using only one parameter
n = 4?
function isSafe(board, row, col) {
for (let i = 0; i < row; i++) {
if (board[i] === col || Math.abs(board[i] - col) === row - i) return false;
}
return true;
}
function solveNQueens(n) {
const board = Array(n).fill(-1);
const results = [];
function backtrack(row) {
if (row === n) {
results.push(board.slice());
return;
}
for (let col = 0; col < n; col++) {
if (isSafe(board, row, col)) {
board[row] = col;
backtrack(row + 1);
board[row] = -1;
}
}
}
backtrack(0);
return results.length;
}
console.log(solveNQueens(4));Solution
Step 1: Understand the code logic
The code uses backtracking to find all valid placements of 4 queens on a 4x4 board. It counts solutions by pushing valid boards to results.Step 2: Recall known N Queens results
For n=4, the number of valid solutions is 2, which matches the returned results length.Final Answer:
2 -> Option DQuick Check:
4 Queens solutions = 2 [OK]
- Assuming 4 queens have more than 2 solutions
- Confusing board representation with count
- Misreading the backtracking logic
function isSafe(board, row, col) {
for (let i = 0; i < row; i++) {
if (board[i] === col || Math.abs(board[i] - col) === row + i) return false;
}
return true;
}Solution
Step 1: Analyze the diagonal attack condition
The diagonal attack is checked by comparing absolute difference of columns to difference of rows. It should berow - i, notrow + i.Step 2: Identify the incorrect expression
The code usesrow + i, which is wrong and causes incorrect safety checks.Final Answer:
The diagonal check uses 'row + i' instead of 'row - i' -> Option CQuick Check:
Diagonal check = row - i [OK]
- Using addition instead of subtraction for diagonal check
- Looping one extra iteration
- Returning true too early
Solution
Step 1: Recall known solution counts for N Queens
For n=5, the known number of distinct solutions is 10.Step 2: Understand why solution count increases
With larger boards, more safe placements exist because queens can be spread out more easily without attacking each other.Final Answer:
10 solutions because more rows allow more queen placements without conflict -> Option BQuick Check:
5 Queens solutions = 10 [OK]
- Assuming no solutions for 5x5
- Confusing unique rows with total solutions
- Underestimating solution count
Ready to prove it?
Pass the test and this pattern moves unknown
