Data Structures19 sections · 729 units
Open in Course

2D Range Sum - Query

Four-term formula

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: O(1)O(1). Four array accesses, three arithmetic operations.

Trace this on a small example. Draw the four rectangles. The formula will make sense.