Python coding

Sums of many rectangles in a grid

Given a grid of integers grid (at least one row and one column) and a list queries, where each query [r1, c1, r2, c2] names the top-left cell (r1, c1) and the bottom-right cell (r2, c2) of a rectangle, return the sum of the cells inside each rectangle, both corners included, in the order given.

There can be many queries: after one pass over the grid, each one should take O(1). Values may be negative and queries may be empty.

Besides the tests, one large input (3,000 rectangles, 70 × 70 grid) with a ~150 ms limit (scaled to your device's speed): brute force won't pass.

  • rect_sums([[2,0,4],[1,5,3],[6,1,0]], [[0,0,1,1],[1,1,2,2],[0,2,2,2]]) → [8,9,7]
  • rect_sums([[1,-2,3,4],[-1,5,-6,2]], [[0,0,1,3],[0,1,1,2],[1,3,1,3]]) → [6,0,2]
  • rect_sums([[7]], [[0,0,0,0]]) → [7]
Ctrl/⌘ + Enter runs · Tab indents
Hint 1

Adding up each rectangle cell by cell costs its area per query. Precompute, for every cell, the sum of the block from the top-left corner down to it.

Hint 2

Give P an extra zero row and column, so P[r][c] covers rows < r and columns < c: P[r+1][c+1] = grid[r][c] + P[r][c+1] + P[r+1][c] - P[r][c].

Hint 3

A rectangle is the block down to its bottom-right corner, minus the strip above it, minus the strip to its left, plus the top-left block that both strips subtracted.

Solution and why it works
pythonO(rows × cols + q), q = number of queries · O(rows × cols)
def rect_sums(grid: list[list[int]], queries: list[list[int]]) -> list[int]:
    rows, cols = len(grid), len(grid[0])
    P = [[0] * (cols + 1) for _ in range(rows + 1)]  # P[r][c] = sum above and left
    for r in range(rows):
        for c in range(cols):
            P[r + 1][c + 1] = grid[r][c] + P[r][c + 1] + P[r + 1][c] - P[r][c]
    return [P[r2 + 1][c2 + 1] - P[r1][c2 + 1] - P[r2 + 1][c1] + P[r1][c1]
            for r1, c1, r2, c2 in queries]

P[r][c] holds the sum of the block above and to the left, so any rectangle is the big block, minus the strip above, minus the strip to the left, plus the corner block both strips removed. Building P is one O(rows × cols) pass and each query is four lookups, instead of its whole area. The extra zero row and column spare rectangles that touch the top or left edge any special case; forgetting to add the corner back is the classic bug.