Data Structures19 sections · 729 units
Open in Course

Vocabulary - 2D Prefix Sum

Rectangle sums

A 2D prefix sum array stores cumulative sums over rectangles.

For matrix matmat: prefix[i][j]=r=0i1c=0j1mat[r][c]prefix[i][j] = \sum_{r=0}^{i-1} \sum_{c=0}^{j-1} mat[r][c] You get the sum of all elements in the rectangle with top-left (0,0)(0, 0) and bottom-right (i1,j1)(i-1, j-1).

Building this array takes O(nm)O(nm) time for an n×mn \times m matrix. After that, any submatrix sum is O(1)O(1).