awelgorithms

Inclusion of a rectangle via four prefixes

Updated

A submatrix sum is four corners of P: P[r2][c2] − P[r1-1][c2] − P[r2][c1-1] + P[r1-1][c1-1]. The plus restores the double-subtracted top-left. Missing index −1 is 0.

What to focus on

Inclusive P[r][c] = sum of a[0..r][0..c]. Draw the big rectangle, subtract the row-above strip, subtract the col-left strip, add back the overlap.

Worked examples

whole

a = [[1, 2], [3, 4]], P = [[1, 3], [4, 10]], r1 = 0, c1 = 0, r2 = 1, c2 = 1
  1. P[1][1]=10
  2. no row above, no col left

Result: 10

one cell

a = [[1, 2], [3, 4]], P = [[1, 3], [4, 10]], r1 = 1, c1 = 1, r2 = 1, c2 = 1
  1. 10 - P[0][1] - P[1][0] + P[0][0]
  2. 10-3-4+1

Result: 4

right column

a = [[1, 2], [3, 4]], P = [[1, 3], [4, 10]], r1 = 0, c1 = 1, r2 = 1, c2 = 1
  1. 10 - 0 - P[1][0] + 0
  2. 10-4

Result: 6

Try it

Write submatrixSum(P, r1, c1, r2, c2). P is an inclusive 2D prefix table. (r1, c1) is the top-left of the query. (r2, c2) is the bottom-right. P[r][c] covers a[0..r][0..c]. Return the four-corner formula. Whole [[1, 2], [3, 4]] → 10 Cell (1, 1) → 4 Right column → 6

The matrix is non-empty integers. Inclusive P is already built. 0 ≤ r1 ≤ r2 < rows and 0 ≤ c1 ≤ c2 < cols. A missing −1 index reads as 0.