Data Structures & AlgorithmsModerateProduct Company SDE · Amazon/Microsoft-style OA

Problem: Count the ways to place n queens on an n × n board so none attack each other.

Problem: Count the ways to place n queens on an n × n board so none attack each other.
def queens(n):
    cols, d1, d2 = set(), set(), set()
    def bt(r):
        if r == n: return 1
        total = 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)
            total += bt(r + 1)
            cols.remove(c); d1.remove(r - c); d2.remove(r + c)
        return total
    return bt(0)
print(queens(4), queens(6), queens(3))
What is printed?
  1. A. 2 4 1
  2. B. 1 4 0
  3. C. 2 6 0
  4. D. 2 4 0

Correct answer: D. 2 4 0

One queen per row; sets of used columns and diagonals (r − c and r + c are constant along each diagonal) give O(1) conflict checks. Known counts: n = 4 → 2, n = 6 → 4 (fewer than n = 5's 10), n = 3 → 0. Backtracking prunes far below n^n.

More Coding Interview Problems questions

Exams that ask this topic