Dodomeki
Sign in

120. Rectangle Sum Queries on a Matrix

Medium

You are given an integer matrix matriz and a list of consultas. Each query contains four indices: [linha1, coluna1, linha2, coluna2], defining an inclusive rectangle within the matrix. Indices are zero-based, and linha1 <= linha2 and coluna1 <= coluna2.

For each query, calculate the sum of the elements in its rectangle. Return a list of sums in the same order as consultas.

Example 1
Input: matriz = [[2, 1, 4], [3, 5, 0]], consultas = [[0, 1, 1, 2], [1, 0, 1, 0]]
Output: [10, 3]
Explanation: The first query sums 1, 4, 5, and 0; the second includes only the element 3.
Example 2
Input: matriz = [[-2, 7], [4, -1]], consultas = [[0, 0, 1, 1], [0, 1, 1, 1]]
Output: [8, 6]
Explanation: The first query sums all elements, and the second sums the right column.
Constraints
  • 1 <= matriz.length <= 500
  • 1 <= matriz[i].length <= 500
  • All rows in `matriz` have the same number of columns
  • -10^4 <= matriz[i][j] <= 10^4
  • 0 <= consultas.length <= 10^5
  • Each query contains four valid integers: [linha1, coluna1, linha2, coluna2], with linha1 <= linha2 and coluna1 <= coluna2
Prefix sumsMatrix
Caso 1
matriz =
[[2,1,4],[3,5,0]]
consultas =
[[0,1,1,2],[1,0,1,0]]
Expected =
[10,3]
Caso 2
matriz =
[[-2,7],[4,-1]]
consultas =
[[0,0,1,1],[0,1,1,1]]
Expected =
[8,6]

Run checks these 2 cases. Submit runs all 11, including hidden ones.