Given a 2D matrix matrix, handle multiple queries of the following type: - Calculate the sum of the elements of 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, int col1, int row2, int col2) Returns the sum of the elements of matrix inside the rectangle defined by its upper left corner (row1, col1) and lower right corner (row2, col2). You must design an algorithm where sumRegion works on O(1) time complexity.
Example 1
Input: operations = ["NumMatrix","sumRegion","sumRegion","sumRegion"], arguments = [[[[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]]],[2,1,4,3],[1,1,2,2],[1,2,2,4]]
Output: [null,8,11,12]
Explanation: Rows 2-4, columns 1-3 contain [2,0,1], [1,0,1] and [0,3,0], which sum to 8. Rows 1-2, columns 1-2 contain [6,3] and [2,0], which sum to 11. Rows 1-2, columns 2-4 contain [3,2,1] and [0,1,5], which sum to 12.
Example 2
Input: operations = ["NumMatrix","sumRegion"], arguments = [[[[1]]],[0,0,0,0]]
Output: [null,1]
Explanation: The rectangle is the single cell (0,0), which holds 1.
Example 3
Input: operations = ["NumMatrix","sumRegion","sumRegion"], arguments = [[[[1,2],[3,4]]],[0,0,1,1],[0,0,0,0]]
Output: [null,10,1]
Explanation: The rectangle (0,0)-(1,1) covers the whole matrix, so 1 + 2 + 3 + 4 = 10. The rectangle (0,0)-(0,0) is just the cell holding 1.
Precompute a table where pre[i][j] is the sum of everything above and to the left of (i, j). Any rectangle sum is then four prefix lookups by inclusion-exclusion.
Run checks all cases above. Submit evaluates all test cases.