Skip to content
Work Free practice Coding course Blog Method Results Why me About Enquire Book a call

Coding · Backtracking

Counting n-queens placements

Hard · Target 25 minutes · Backtracking · Type asked atAmazonBloomberg

Place n queens on an n × n chessboard so that no two attack each other: no two share a row, a column or a diagonal. Return the number of distinct placements.

Examples

InputOutputWhy
n = 42Columns by row: 2, 4, 1, 3 and its mirror 3, 1, 4, 2.
n = 11One queen on one square.
n = 30No placement exists for n = 2 or n = 3.

Constraints

  • 1 ≤ n ≤ 12

Hints

Hint 1

Two queens in one row always attack each other, so each row holds exactly one queen. What does that reduce the problem to?

Hint 2

Place queens row by row. For the current row, which columns are still safe given the queens above?

Hint 3

Keep three sets: columns in use, "\" diagonals in use (row − column constant) and "/" diagonals in use (row + column constant). A square is safe if it is in none of them.

Console⌘/Ctrl + Enter runs

Write a solution and run it against the real test table.


Keep going

Preparing for a real process? Quant interview preparation, or book a free 20-minute call.