What is the N-Queens problem?
Why Interviewers Ask This
This question targets practical, hands-on experience with Data Structures & Algorithms. Interviewers want to see if you've worked with these concepts in real projects, not just read about them. Strong answers include concrete examples.
Answer
The N-Queens problem places N queens on an N×N chessboard such that no two queens attack each other (no same row, column, or diagonal). It's the classic backtracking problem. Algorithm: place queens row by row; for each row, try each column; check if safe (no conflict with previously placed queens); if safe, place and recurse to next row; if no valid column, backtrack (remove last queen, try next column). Safety check: O(n) — check column, both diagonals. Optimization: use sets to track occupied columns and diagonals (row-col = const for one diagonal, row+col = const for the other). Backtracking implementation: def solve(row): if row == n: record solution; return; for col in range(n): if col not in cols and (row-col) not in diag1 and (row+col) not in diag2: place, recurse(row+1), remove. Time: O(n!) worst case (pruning makes it much faster in practice). Space: O(n) recursion depth. Solutions: N=8 has 92 solutions. Generalizations: (1) Count solutions vs find one; (2) N-Rooks (only row/column constraints); (3) N-Knights; (4) Sudoku solver. Backtracking pattern: make a choice → recurse → undo the choice (backtrack). Used in all constraint satisfaction problems: Sudoku, crosswords, map coloring, Hamiltonian paths.
Common Mistake
Candidates often give textbook answers here. Interviewers are more impressed when you relate the concept to a specific problem you solved in a real Data Structures & Algorithms project.