To query sum over rectangle to , use inclusion-exclusion:
where is the prefix sum to .
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 queries and updates instead of queries with updates.