Skip to the code
+25 XP

#52 Heatmap Region Totals

medium

A click heatmap stores click counts per cell in grid. Users drag selection boxes, given in queries as [r1, c1, r2, c2]: the top-left and bottom-right cells, both included.

Write regionTotals(grid, queries) that returns the total clicks inside each box, in order. Each query should take O(1) after setup.

Example 1

Input: grid = [[3,0,1],[5,6,3],[1,2,0]], queries = [[1,1,2,2],[0,0,0,2],[0,0,2,2]]
Output: [11,4,21]

The bottom-right 2 by 2 block is 6 + 3 + 2 + 0 = 11, the top row is 4, and the whole grid is 21.

Example 2

Input: grid = [[7]], queries = [[0,0,0,0]]
Output: [7]

A one-cell grid and a one-cell box.

Constraints

  • 1 <= rows, cols <= 400
  • -10^4 <= grid[r][c] <= 10^4
  • 0 <= queries.length <= 10^5
  • 0 <= r1 <= r2 < rows, 0 <= c1 <= c2 < cols
Saved in this browser

Run tries your code on the examples. Submit runs every test, including hidden edge cases and big inputs that check your code is fast enough, and solves the problem when they all pass.

Ctrl + Enter runs, Ctrl + Shift + Enter submits (⌘ on a Mac).