Stealth Interview
  • Features
  • Pricing
  • Blog
  • Login
  • Sign up

Leetcode #304: Range Sum Query 2D - Immutable

In this guide, we solve Leetcode #304 Range Sum Query 2D - Immutable in Python and focus on the core idea that makes the solution efficient.

You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Leetcode

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.

Quick Facts

  • Difficulty: Medium
  • Premium: No
  • Tags: Design, Array, Matrix, Prefix Sum

Intuition

Range queries become simple once we precompute cumulative sums.

We can transform subarray conditions into prefix comparisons.

Approach

Compute prefix sums and use a map to find matching prefixes.

This avoids nested loops while keeping the logic clear.

Steps:

  • Compute prefix sums.
  • Use a map to find valid ranges.
  • Update the answer.

Example

Input ["NumMatrix", "sumRegion", "sumRegion", "sumRegion"] [[[[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 NumMatrix numMatrix = new NumMatrix([[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]]); 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)

Python Solution

class NumMatrix: def __init__(self, matrix: List[List[int]]): m, n = len(matrix), len(matrix[0]) self.s = [[0] * (n + 1) for _ in range(m + 1)] for i, row in enumerate(matrix): for j, v in enumerate(row): self.s[i + 1][j + 1] = ( self.s[i][j + 1] + self.s[i + 1][j] - self.s[i][j] + v ) def sumRegion(self, row1: int, col1: int, row2: int, col2: int) -> int: return ( self.s[row2 + 1][col2 + 1] - self.s[row2 + 1][col1] - self.s[row1][col2 + 1] + self.s[row1][col1] ) # Your NumMatrix object will be instantiated and called as such: # obj = NumMatrix(matrix) # param_1 = obj.sumRegion(row1,col1,row2,col2)

Complexity

The time complexity is O(n). The space complexity is O(m×n)O(m \times n)O(m×n).

Edge Cases and Pitfalls

Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.

Summary

This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.


Ace your next coding interview

We're here to help you ace your next coding interview.

Subscribe
Stealth Interview
© 2026 Stealth Interview®Stealth Interview is a registered trademark. All rights reserved.
Product
  • Blog
  • Pricing
Company
  • Terms of Service
  • Privacy Policy