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.
Examples
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]