143. Range Sum Query 2D

HardArrayArray

Given a 2D matrix and a list of queries [r1,c1,r2,c2] (inclusive rectangle corners), return the sum of all query results. Use a 2D prefix-sum for O(1) per query. Input: JSON {matrix, queries}.

Input: JSON {matrix, queries}.

Output: Integer — total of all query sums.

Examples

Example 1
Input: {"matrix":[[3,0,1,4,2],[5,6,3,2,1],[1,2,0,1,5],[4,1,0,1,7],[1,0,3,0,5]],"queries":[[2,1,4,3],[1,1,2,2],[1,2,2,4]]}
Output: 33
Explanation: Sum of the three rectangle sums (8+11+14).
Example 2
Input: {"matrix":[[1]],"queries":[[0,0,0,0]]}
Output: 1
Explanation: Single cell.

Constraints

Asked by

AmazonGoogleMicrosoftMetaAdobe
Solve this problem in the editor →