Orchard Plot Totals

Medium · Prefix Sums · about 25 min

An orchard is planted as a grid: grid[r][c] is the number of apples picked from the tree in row r, column c. A buyer asks about many rectangular plots. Each query [r1, c1, r2, c2] names the top-left tree (r1, c1) and the bottom-right tree (r2, c2) of a plot, both included.

Return a list with the total apples for each query, in the same order.

  • The grid has 1 to 500 rows and 1 to 500 columns. Values can be negative (adjustments for spoiled fruit).
  • Every query has 0 <= r1 <= r2 < rows and 0 <= c1 <= c2 < columns. There can be up to 100,000 queries.
  • Aim for O(1) work per query after one setup pass.

Example:

plot_harvest_totals([[3, 0, 1], [5, 6, 3], [1, 2, 0]], [[0, 0, 1, 1], [1, 1, 2, 2], [2, 0, 2, 2]]) → [14, 11, 3]

Hints

  • First solve the 1-D version: a running total with a leading 0 answers any range in O(1).
  • In 2-D, store the total of every rectangle that starts at the top-left corner, with an extra row and column of zeros.
  • A plot is a big corner rectangle minus two strips, plus the small corner that was removed twice.

Learn the pattern first: the Prefix Sums lesson.

More Prefix Sums problems