Range Sum Query 2D – Immutable
Problem Statement
You are given a 2D grid of integers matrix that never changes. After that, you will be asked many questions of the form "what is the sum of every cell inside this rectangle?" A rectangle is given by its top-left corner (row1, col1) and its bottom-right corner (row2, col2), both included.
Write a class NumMatrix:
NumMatrix(vector<vector<int>>& matrix)receives the grid once.int sumRegion(int row1, int col1, int row2, int col2)returns the sum ofmatrix[r][c]for allrow1 ≤ r ≤ row2andcol1 ≤ c ≤ col2.
Each query must run in O(1) time.
The grid matrix (given once, to the constructor), followed by many calls sumRegion(row1, col1, row2, col2).
For each sumRegion call, the sum of all cells inside that rectangle.
Rows 2–4, columns 1–3: (2+0+1) + (1+0+1) + (0+3+0) = 8. Rows 1–2, columns 1–2: 6+3+2+0 = 11. Rows 1–2, columns 2–4: 3+2+1+0+1+5 = 12.
- • 1 ≤ m, n ≤ 200 (m rows, n columns)
- • −10^4 ≤ matrix[i][j] ≤ 10^4
- • 0 ≤ row1 ≤ row2 < m and 0 ≤ col1 ≤ col2 < n
- • At most 10^4 calls to sumRegion
- • The largest total is 200 · 200 · 10^4 = 4·10^8, so `int` is enough.
Pattern Recognition Clues
Recognising these key signals in the problem description immediately identifies the pattern:
Approach Complexity Ladder
Keep the grid; each query loops over every cell in the rectangle
Prefix sum for every row; a query adds one O(1) row-sum per row
Corner-block totals in an (m+1)×(n+1) table; each query is 4 lookups
Store the grid. For each query, loop over the rows row1..row2 and, inside, the columns col1..col2, and add every cell.
Recognition rule for this sub-pattern:
Unlock Complete Visual Walkthrough & Optimal C++
The interactive animated dry-run player, optimized C++ implementation, state invariant derivations, and edge-case breakdown for this question are part of Brute2Best Pro. The anchor question of every sub-pattern is completely free.
First anchor question per pattern, Part 1 LLD & Module 1 C++ basics are 100% Free forever.
How this concept connects to System Design & C++ Systems
Top engineering interviews test whether you understand how algorithms like Prefix Sum translate into production architectures and low-level memory mechanics.
Foundations: Object-Oriented Principles in C++23
Class invariants, pure virtual interfaces, and RAII smart pointers.
Food Delivery System (Zomato Architecture)
Real-world machine coding application of algorithms and design patterns.
Pointers vs References Deep Dive
Pointer arithmetic and memory layout under the hood.
Virtual Method Table (vtable) & Memory Layout
Polymorphism, vptr overhead, and multiple inheritance in memory.