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?- A. 10 10
- B. 8 4
- C. 10 0
- 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
- Problem: Count the DISTINCT subsets (as multisets) of a list that contains duplicates, using backtracking that skips equal siblings…
- Problem: In an array every value appears twice except two values that appear once. Find those two in O(n) time and O(1) space. python def…
- Building a binary heap from n given keys: what are the worst-case costs of (i) bottom-up heapify and (ii) n successive inserts into an…
- In Java 8+, many keys that are Comparable and all land in ONE HashMap bucket. What is the worst-case cost of get() on that bucket once it…
- Problem: For each day, how many days until a strictly warmer day (0 if none)? python def wait(t): res, st = [0] len(t), [] for i, x in…
- Problem: The span of a stock on a day is the number of consecutive days up to and including it with price ≤ that day's price. python def…