Data Structures & AlgorithmsHardAmazon · Microsoft OA

Problem: Count the ways to place n non-attacking queens on an n × n board.

Problem: Count the ways to place n non-attacking queens on an n × n board.
def queens(n):
    cols, d1, d2 = set(), set(), set()
    def go(r):
        if r == n: return 1
        t = 0
        for c in range(n):
            if c in cols or r - c in d1 or r + c in d2: continue
            cols.add(c); d1.add(r - c); d2.add(r + c)
            t += go(r + 1)
            cols.remove(c); d1.remove(r - c); d2.remove(r + c)
        return t
    return go(0)
print(queens(5), queens(6))
What is printed?
  1. A. 10 10
  2. B. 8 4
  3. C. 10 0
  4. D. 10 4

Correct answer: D. 10 4

Backtracking with column and both diagonal sets (r − c and r + c) counts 10 solutions for n = 5 but only 4 for n = 6; the count is not monotonic in n (n = 2 and 3 have none).

More Coding Interview Problems questions

Exams that ask this topic