Submatrix Sum Query

Data Structure Matrix Prefix Sum

Given a 2D array of integers called matrix, implement a class (or module) named NumMatrix that provides an efficient way to perform sum queries over submatrices. Specifically, the class should include:

  1. A constructor that takes the 2D array matrix as input.

  2. A method sumRegion(row1, col1, row2, col2) that returns the sum of all elements within the rectangle defined by the upper left corner (row1, col1) and the lower right corner (row2, col2) (inclusive).

Constraints:

  • You may assume that the matrix does not change after initialization.
  • Optimize your solution for multiple calls to sumRegion such that each query is as fast as possible. Consider pre-processing the matrix if needed.

Example:
Given the 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]
]

Calling sumRegion(2, 1, 4, 3) should return 8.

Create a complete implementation in the programming language of your choice.