Advertisement

Range Sum Query 2D - Immutable - LeetCode 304 Solution

Range Sum Query 2D - Immutable - Complete Solution Guide

Range Sum Query 2D - Immutable is LeetCode problem 304, a Medium level challenge. This complete guide provides step-by-step explanations, multiple solution approaches, and optimized code in python3, java, cpp, c.

Problem Statement

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) a

Detailed Explanation

The problem asks us to implement a `NumMatrix` class that can efficiently calculate the sum of elements within a rectangular region of a given 2D matrix. We need to pre-process the matrix in the constructor and then provide a `sumRegion` method that returns the sum of the elements within a given rectangle (defined by its top-left and bottom-right corners) in O(1) time. The main constraint is to make the `sumRegion` method as fast as possible, which suggests pre-computation during initialization.

Solution Approach

The solution uses a 2D prefix sum (or cumulative sum) approach. During the `NumMatrix` constructor, we create a `dp` table of size (m+1) x (n+1), where `dp[i][j]` stores the sum of all elements in the submatrix `matrix[0...i-1][0...j-1]`. The `sumRegion` method calculates the sum of the desired rectangle by using the pre-computed sums in the `dp` table. Specifically, it uses the formula: `sumRegion = dp[row2+1][col2+1] - dp[row1][col2+1] - dp[row2+1][col1] + dp[row1][col1]` This formula effectively calculates the sum of the target rectangle by adding the sum of the entire rectangle from (0,0) to (row2, col2), and then subtracting the sums of the rectangles above and to the left of the desired area. Finally, it adds the overlapping region that was subtracted twice.

Step-by-Step Algorithm

  1. Step 1: Initialize the `dp` table with dimensions (m+1) x (n+1) and fill it with zeros.
  2. Step 2: Iterate through the original matrix `matrix` from row 0 to m-1 and column 0 to n-1.
  3. Step 3: For each element `matrix[r][c]`, calculate the cumulative sum `dp[r+1][c+1]` using the formula: `dp[r+1][c+1] = dp[r][c+1] + dp[r+1][c] - dp[r][c] + matrix[r][c]`.
  4. Step 4: In the `sumRegion` method, given `row1`, `col1`, `row2`, and `col2`, return the sum of the rectangle using the formula: `dp[row2+1][col2+1] - dp[row1][col2+1] - dp[row2+1][col1] + dp[row1][col1]`.

Key Insights

  • Insight 1: Prefix sum technique can be extended to two dimensions to pre-compute sums of regions efficiently.
  • Insight 2: By pre-computing cumulative sums, we can calculate the sum of any sub-rectangle using a constant number of operations in the `sumRegion` method.
  • Insight 3: Using a DP table with an extra row and column (initialized to 0) simplifies the calculation of cumulative sums and avoids boundary checks.

Complexity Analysis

Time Complexity: O(m*n)

Space Complexity: O(m*n)

Topics

This problem involves: Array, Design, Matrix, Prefix Sum.

Companies

Asked at: Applied Intuition, DoorDash, Lyft, Nvidia, Snowflake, Upstart.