Data Structures19 sections · 729 units
Open in Course

2D Range Sum Query

Rectangle queries

To query sum over rectangle (r1,c1)(r_1, c_1) to (r2,c2)(r_2, c_2), use inclusion-exclusion:

sum=Q(r2,c2)Q(r11,c2)Q(r2,c11)+Q(r11,c11)\text{sum} = Q(r_2, c_2) - Q(r_1-1, c_2) - Q(r_2, c_1-1) + Q(r_1-1, c_1-1)

where Q(x,y)Q(x, y) is the prefix sum to (x,y)(x, y).

def rangeSum(r1, c1, r2, c2):
    return (query2D(r2, c2)
          - query2D(r1-1, c2)
          - query2D(r2, c1-1)
          + query2D(r1-1, c1-1))

You're applying the same inclusion-exclusion principle used for 2D prefix sums, but now with O(lognlogm)O(\log n \log m) queries and updates instead of O(1)O(1) queries with O(nm)O(nm) updates.