Technique
2D Prefix Sums
Extend prefix sums to grids with inclusion-exclusion so any sub-rectangle sum is O(1).
Learn firstPrefix Sum
0%
mastery
0/3 solved
0/3 solved
Recognise it
The signal
many rectangle-sum queries
1Brute force
Sum each rectangle cell by cell.
2The observation
Per-query O(RC) sums: four lookups via inclusion-exclusion.
3Why it works
P[i][j] = sum of the rectangle [0..i) x [0..j).
Reach for it when
- +count sub-rectangles with a property using O(R2 C) enumeration
Not when
- ×updates between queries (2D Fenwick)
Practice
0/3 solved
- Range Sum Query 2D - ImmutableMeta, GoogleMedium
- Forest QueriesCSESMedium
- All Letter Subgrid Count IICSESHard
Pitfalls
Misconceptions
- !sign errors in inclusion-exclusion