Skip to the solution
HardDSA11 min read

How do you solve the N-Queens problem?

563 views

The problem

Question presented to candidate: "Place n queens on an n by n chessboard so that no two attack each other. Write a Python function that returns every solution, and then tell me how you would only count them for n up to 12."

What a strong answer should cover:

  • Place one queen per row, so a solution is a list queens[row] = col; this turns nยฒ cells into n decisions.
  • Backtracking with choose / explore / un-choose, pruning a column as soon as it is attacked.
  • O(1) safety checks using three sets: columns, r - c and r + c.
  • Complexity: O(n!) upper bound on the search, O(n) extra space plus the output; 92 solutions for n = 8.
  • Python details: append queens[:] (a copy), use set or list[bool] for the taken markers, recursion depth is only n so the default limit of 1000 is not a problem, and the bitmask version needs & full because Python ints never overflow.

Clarifying questions expected:

  • Do you want every board (as strings) or only the number of solutions?
  • What range of n should I expect? (It decides whether a bitmask counter is worth it.)

Code / implementation expected: Yes โ€” a recursive solve_n_queens(n) with three sets in Python 3, and optionally a bitmask counter.

  • dsa
  • backtracking

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

11 min read ยท 14 sections

Python code

Edit the code and run it here. Each printed line with an expected value becomes a test.

PythonAll solutions as boards for n = 4, solution counts for n = 0..8
PythonBrute force over permutations vs backtracking: work counted for n = 4..8
PythonN-Queens II: counting solutions for n = 1..12 with bitmasks

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 147 of 154 in DSA

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

All DSA questions
Up nextHard

Design an LRU Cache with O(1) get and put โ€” why doubly linked list + hash map?

Continue