Data Structures & AlgorithmsModerateInfosys SP/DSE · Product Company SDE

Problem: A 3 × 4 grid of crop yields must answer 'total yield in rectangle (r1, c1)–(r2, c2)' in O(1) using a 2-D prefix table with one extra row and column.

Problem: A 3 × 4 grid of crop yields must answer 'total yield in rectangle (r1, c1)–(r2, c2)' in O(1) using a 2-D prefix table with one extra row and column.
g = [[1, 2, 3, 4],
     [5, 6, 7, 8],
     [9, 1, 2, 3]]
R, C = len(g), len(g[0])
P = [[0] * (C + 1) for _ in range(R + 1)]
for i in range(R):
    for j in range(C):
        P[i+1][j+1] = g[i][j] + P[i][j+1] + P[i+1][j] - P[i][j]
def rect(r1, c1, r2, c2):
    return P[r2+1][c2+1] - P[r1][c2+1] - P[r2+1][c1] + P[r1][c1]
print(rect(1, 1, 2, 2), rect(0, 0, 2, 3), rect(0, 3, 2, 3))
What is printed?
  1. A. 16 51 15
  2. B. 15 51 15
  3. C. 16 51 12
  4. D. 16 50 15

Correct answer: A. 16 51 15

P[i][j] holds the sum of the top-left i × j block; a rectangle is P(bottom-right) minus the strip above minus the strip to the left plus the doubly-subtracted corner (inclusion–exclusion). Rows 1–2, cols 1–2: 6 + 7 + 1 + 2 = 16. The whole grid: 10 + 26 + 15 = 51. Column 3: 4 + 8 + 3 = 15. Build O(R·C), each query O(1).

More Coding Interview Problems questions

Exams that ask this topic