Back to photostream

Range Sum Query 2D - Immutable LeetCode Solution

Problem Statement

Range Sum Query 2D - Immutable LeetCode Solution - Given a 2D matrix, handle multiple queries of the following type:

 

- Calculate the sum of the elements of the matrix inside the rectangle defined by its upper left corner (row1, col1) and lower right corner (row2, col2).

 

Implement the NumMatrix class:

 

- NumMatrix(int matrix) Initializes the object with the integer matrix matrix.

- int sumRegion(int row1, intcol1, int row2, int col2) Returns the sum of the elements of the matrix inside the rectangle defined by its upper left corner (row1, col) and lower right corner (row2, col2).

 

 

 

Example 1:

 

Input

 

, , , , ]], , , ]

 

Output

 

Explanation

NumMatrix numMatrix = new NumMatrix(, , , , ]);

numMatrix.sumRegion(2, 1, 4, 3); return 8 (i.e sum of the red rectangle)

numMatrix.sumRegion(1, 1, 2, 2); return 11 (i.e sum of the green rectangle)

numMatrix.sumRegion(1, 2, 2, 4); return 12 (i.e sum of the blue rectangle)

Approach

Idea:

First, we make a cumulative sum for each row. Then, we use this new cumulative array and subtract the last int in our new "sumRegion" row from the first number in that "numMatrix" row. This shows us how much each row is and after we find the sums of each row, add them together to figure out the sum of the "sumRegion". For regions that are taller than they are wide, do this same process but with the columns instead. The link down below shows the process written out.

Code

Python

 

www.tutorialcup.com/leetcode-solutions/range-sum-query-2d...

14 views
0 faves
0 comments
Uploaded on July 12, 2022