304 Range Sum Query 2D - Immutable

Given a 2D matrixmatrix, find the sum of the elements inside the rectangle defined by its upper left corner (row1,col1) and lower right corner (row2,col2).

Range Sum Query 2D The above rectangle (with the red border) is defined by (row1, col1) =(2, 1)and (row2, col2) =(4, 3), which contains sum =8.

Example:

Given 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]
]

sumRegion(2, 1, 4, 3) -
>
 8
sumRegion(1, 1, 2, 2) -
>
 11
sumRegion(1, 2, 2, 4) -
>
 12

Complexity: Linear to the number of elements n, in both time and space.

The Idea: We begin by building what is a called an integral matrix. An integral matrix uses the same principles as an integral array , but just expanded to 2 dimensions. An integral array is just the accumulative summation of elements within the array. For example:

Using this array, the idea is that now we can represent any cumulative subset of the array in O(1) time. Intuitively, this mean taking every accumulated to the end point, and subtracting it with the access we don't care about.

Using the same principles, we can generalize this to 2 dimensions.

Then a summation would look like this. Notice we are subtracting the upper corner twice, so we have to add it back in, just in set theory where (A or B) = A + B - (A and B)

Some Testing:

Last updated

Was this helpful?