#304

Range Sum Query 2D - Immutable

Medium 2D prefix sum

  1. Read
  2. Understand
  3. Hints
  4. Approach
  5. Solution
  6. Solved

?The problem

Answer many queries for the sum of a rectangle inside a fixed matrix.

This is a short summary in our own words. Read the full statement and examples on LeetCode: open problem ↗

◎Understanding

Really asking: sum of any rectangle in a fixed grid, fast.

Why this works: P[r][c] holds the sum of everything above and to the left. A rectangle is the big corner sum minus the strip above and the strip to the left, plus the corner that got subtracted twice.

Example: rectangle rows 1..2, cols 1..2

answer = P[3][3] - P[1][3] - P[3][1] + P[1][1](whole) - (top strip) - (left strip) + (top-left corner)

✦Hints open one at a time

↗Approach

</>Solution (Java)

!Common mistake

Forgetting to add back the top-left corner, which was subtracted twice.