Data Structures & Algorithms Backtracking
💡
Exercise 147

N-Queens 30 XP Hard

LeetCode Ctrl+Enter Run Ctrl+S Save

This is LeetCode #51: N-Queens — the ultimate backtracking challenge! 👑

💡 Think of it like this: Place N queens on an N×N chessboard so no two queens can attack each other. Queens can attack in any direction — horizontal, vertical, and both diagonals. For a 4×4 board, how many valid arrangements exist?

# 4-Queens has 2 solutions: # Solution 1: Solution 2: # . Q . . . . Q . # . . . Q Q . . . # Q . . . . . . Q # . . Q . . Q . .

The Backtracking Approach: Place queens one row at a time. For each row, try each column. If it's safe (no conflicts with queens above), place it and move to the next row.

How to check if a position is safe:

  • 📏 Column check: Is any queen already in this column? → Use a set
  • ↘️ Diagonal check: Queen at (r,c) attacks along r - c (constant for each diagonal) → Use a set
  • ↙️ Anti-diagonal check: Queen at (r,c) attacks along r + c → Use a set
  • ✨ No need to check rows — we place exactly one queen per row!

💭 Now it's your turn! Using the approach above, implement your solution in the editor. You've got this! 💪

Why 3 sets work: For any diagonal going ↘, all cells have the same r-c. For any diagonal going ↙, all cells have the same r+c. Checking membership in a set is O(1)!

Complexity: Time O(n!) — much better than O(n^n) brute force. Space O(n) for the sets and recursion stack.

📋 Instructions
Find the number of solutions for the 4-Queens problem.
Place queens row by row. Use sets for columns, diagonals (r-c), anti-diagonals (r+c). Try each column; if safe, place and recurse. After recursion, remove from all sets.
⚠️ Try solving it yourself first — you'll learn more!
def solveNQueens(n):
    cols = set()
    diag = set()       # r - c identifies each diagonal
    anti_diag = set()  # r + c identifies each anti-diagonal
    count = 0
    
    def backtrack(row):
        nonlocal count
        if row == n:        # All queens placed!
            count += 1
            return
        for col in range(n):
            if col in cols or (row-col) in diag or (row+col) in anti_diag:
                continue    # Not safe, skip
            cols.add(col)              # Place queen
            diag.add(row-col)
            anti_diag.add(row+col)
            backtrack(row + 1)          # Try next row
            cols.remove(col)           # Backtrack!
            diag.remove(row-col)
            anti_diag.remove(row+col)
    
    backtrack(0)
    return count
🧪 Test Cases
Input
solveNQueens(4)
Expected
2
Test case 1
main.py
Hi! I'm Rex 👋
Output
Ready. Press ▶ Run or Ctrl+Enter.