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?- A. 2 4 1
- B. 1 4 0
- C. 2 6 0
- 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
- Problem: Find whether a word exists in a letter grid by moving to adjacent (up/down/left/right) cells without reusing a cell. python def…
- Problem: List all combinations of k numbers from 1..n that sum to s (each number used at most once). python def combo(k, s, n=9): out = []…
- Problem: The recursive function below counts calls. How many times is f called for f(5)? python calls = 0 def f(n): global calls calls +=…
- Problem: Compute xⁿ by fast exponentiation (recursive squaring) and count multiplications. python mults = 0 def power(x, n): global mults…
- Problem: Generate the letter combinations a phone keypad number can represent and report how many there are. python from itertools import…
- Problem: Count set bits for each number 0..n using DP on the lowest bit. python def bits(n): r = [0] (n + 1) for i in range(1, n + 1)…