Data Structures & AlgorithmsHardProduct Company SDE · CP practice

Problem: How many ways are there to place 2 non-attacking rooks on a 4 x 4 board? Run the code.

Problem: How many ways are there to place 2 non-attacking rooks on a 4 x 4 board? Run the code.
from itertools import combinations
cells = [(r, c) for r in range(4) for c in range(4)]
print(sum(1 for a, b in combinations(cells, 2) if a[0] != b[0] and a[1] != b[1]))
What is printed?
  1. A. 144
  2. B. 120
  3. C. 72
  4. D. 36

Correct answer: C. 72

Choose 2 rows and 2 columns and match them in 2 ways: 6 · 6 · 2 = 72. Ordered placements give 144, all pairs of cells number 120, and forgetting the factor 2 gives 36.

More Coding Interview Problems questions

Exams that ask this topic