Data Structures & AlgorithmsHardCodeforces Div2 C · prefix sums

Problem: Using 2D prefix sums on M = [[1,2,3],[4,5,6],[7,8,9]], what is the sum of the rectangle with rows 1..2 and columns 1..2 (0-indexed, inclusive)?

Problem: Using 2D prefix sums on M = [[1,2,3],[4,5,6],[7,8,9]], what is the sum of the rectangle with rows 1..2 and columns 1..2 (0-indexed, inclusive)?
M = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
n, m = 3, 3
P = [[0] * (m + 1) for _ in range(n + 1)]
for i in range(n):
    for j in range(m):
        P[i + 1][j + 1] = M[i][j] + P[i][j + 1] + P[i + 1][j] - P[i][j]
r1, c1, r2, c2 = 1, 1, 2, 2
print(P[r2 + 1][c2 + 1] - P[r1][c2 + 1] - P[r2 + 1][c1] + P[r1][c1])
What is printed?
  1. A. 24
  2. B. 30
  3. C. 22
  4. D. 28

Correct answer: D. 28

The rectangle is 5 + 6 + 8 + 9 = 28. The inclusion-exclusion step subtracts the two strips and adds back the corner counted twice.

More Coding Interview Problems questions

Exams that ask this topic