Skip to contentKEEP THE CRAFTTHE SANCTUARY

Answer Matrix Region Sums

Build a 2D prefix-sum table once, then answer each rectangle sum from four corners.

The problem

Implement matrix_region_sums(matrix, queries). matrix is a non-empty grid of integers where every row has the same length. Each query is [top, left, bottom, right] and describes the rectangle from row top to row bottom and from column left to column right, all ends included. Return a list with the sum of the numbers inside each rectangle, in query order. There can be many queries, so answer each one in O(1) after some preparation.

Starter code

def matrix_region_sums(matrix, queries):
    pass

Public examples

  1. matrix = [[1, 2, 3], [4, 5, 6]], queries = [[0, 0, 0, 2], [0, 1, 1, 2], [1, 1, 1, 2]]gives[6, 16, 11]
  2. matrix = [[5, 1], [2, 7]], queries = [[1, 1, 1, 1]]gives[7]

Solving it in the practice book needs an active paid plan.

Open it in the practice book
One thought at a time.