Skip to main content

N-Queens

Place n queens on an n×n chessboard such that no two queens attack each other Return all distinct solutions as board configurations 'Q' = queen, '.' = empty space Example: n = 4 => [[".Q..","...Q","Q...","..Q."],["..Q.","Q...","...Q",".Q.."]]

N-Queens is about exploring choices without getting lost—choose, recurse, undo, repeat. It's a hard one for a reason: it stresses structured exploration when the rules pile up. The gotcha is duplicates and dead ends—good pruning and ordering rules make this manageable.

Examples

You write

solve_n_queens(n: int)

  1. Example 1

    Input
    n = 4
    returns
    [[".Q..","...Q","Q...","..Q."],["..Q.","Q...","...Q",".Q.."]]
  2. Example 2

    Input
    n = 1
    returns
    [["Q"]]

The pattern behind it

Arrays & Hashing

I reach for it when

  • You catch yourself scanning the array again for every element.
  • The problem asks about duplicates, pairs, counts or groups.

Say this before you type. Say what the key is and what the value remembers, before you write the loop.

All 127 Arrays & Hashing problems

Backtracking

I reach for it when

  • The question asks for all combinations, permutations or placements.
  • You make a choice, explore it, and may need to take it back.

Say this before you type. Say the choice, the stopping rule, and the earliest moment you can prune.

All 15 Backtracking problems

Meet Coco

Coco is an AI study partner, not a person. She listens while you explain your code, asks what a line does and never hands you the fix. Sign in free to type with Coco, up to a daily limit. The editor and Run stay open without an account. Anyone can open the editor and run their code.

1Find All N-Queens Solutionshard

Prep guides that list this problem

Our company tags come from public interview write-ups. None of these is a confirmed question.