Build a 2D prefix table
Updated
Fill P left-to-right, top-to-bottom. Recurrence: P[r][c] = a[r][c] + up + left − upLeft, where missing neighbors are 0. The minus kills the double-counted top-left block.
What to focus on
Inclusive layout, same shape as a. First cell P[0][0]=a[0][0]. Every other cell uses already-filled P. One pass, Θ(rows*cols) writes.
Worked examples
2x2
a = [[1, 2], [3, 4]]- P[0][0]=1
- P[0][1]=2+1=3
- P[1][0]=3+1=4
- P[1][1]=4+3+4-1=10
Result: P = [[1, 3], [4, 10]]
2x3
a = [[1, 4, 9], [1, 4, 9]]- row0 → [1, 5, 14]
- P[1][0]=1+1=2
- P[1][1]=4+5+2-1=10
- P[1][2]=9+14+10-5=28
Result: P = [[1, 5, 14], [2, 10, 28]]
top row only
a = [[1, 2], [3, 4]], first row- P[0][0]=1
- P[0][1]=3
- do not touch row 1 yet
Result: P[0] = [1, 3]
Try it
Write build2DPrefix(a). a is the matrix. Inclusive P[r][c] is the sum of a[0..r][0..c]. Return P. [[1, 2], [3, 4]] → [[1, 3], [4, 10]] [[1, 4, 9], [1, 4, 9]] → [[1, 5, 14], [2, 10, 28]]
The matrix is non-empty integers with at least one row and one column. Inclusive layout, same shape as a. P[r][c] covers a[0..r][0..c].