Querying uses the inclusion-exclusion formula:
function sumRegion(row1, col1, row2, col2)
return prefix[row2+1][col2+1]
- prefix[row1][col2+1]
- prefix[row2+1][col1]
+ prefix[row1][col1]
Time: . Four array accesses, three arithmetic operations.
Trace this on a small example. Draw the four rectangles. The formula will make sense.