Submatrix Sum
Range Query / 2D Prefix Sum (Optimized)Solved Oct 23, 2025
Go step by step: try it yourself before the video and the visual. Progress saves on this device.
0 / 130 pointsSolved (Medium) 0/40Reviews 0/50Mastered 0/25Practice steps 0/15
Step 1
Know these before you start
Practise each one here, or tick what you already know
Watch the concept video if the pattern is new to you.
Step 2
Try it on paper
5–10 minutes, no code yet
ProblemProblem statementGiven a matrix of size N × N and four integers (i, j, k, l), calculate the sum of the sub-matrix from the top-left coordinate (i, j) to the bottom-right coordinate (k, l).ReadHide
Problem Description
Given a matrix of size N × N and four integers (i, j, k, l), calculate the sum of the sub-matrix from the top-left coordinate (i, j) to the bottom-right coordinate (k, l).
Example
Input: 3 1 1 2 2 1 2 3 4 5 6 7 8 9
Output: 28
Explanation: Sum of elements (5, 6, 8, 9) = 28.
Code it here
Tab / Shift+Tab indent · ⌘/Ctrl+/ comments · ⌘/Ctrl+Enter runs · Esc leaves the editor
Step 6
Get it accepted
All test cases pass
Step 7
Review it so it sticks
Re-solve from memory after
The step that matters most: without reviews most of a solved problem fades within weeks. Three short re-solves, each just as you start to forget, are what make it yours.
Your notes
Three lines in your own words. They come back with this problem's reviews, so you can check yourself after recalling the solution.
Solve it yourself before you look
Reading the solution first feels like progress, but it makes the next similar problem — and the interview version — much harder, because you skipped the part where you figure it out. Give it an honest 20–30 minutes. Stuck? Re-read the pattern, watch the concept video, or try the brute force first.
Hidden: approach · solution code · optimal solution
Approach
Brute force sum for small N (O(N^2)) or 2D Prefix Sum for optimization (O(1) query).
Approaches
1. Brute Force Summation - O(N²) per Query (Worst Case)
Idea: Directly iterate over the specified submatrix boundaries. Loop from row r=i to k and column c=j to l, adding each element.
Time: O((k-i) · (l-j)), which is O(N²) in the worst case (querying the entire matrix).
Space: O(N²) (to store the matrix).
2. 2D Prefix Sum (Optimized) - O(1) per Query ⭐
Idea: Pre-calculate the sum of all sub-matrices starting from (0, 0) to any point (r, c). This is stored in a PrefixSum matrix.
The sum of the sub-matrix from (i, j) to (k, l) is then calculated in O(1) using the inclusion-exclusion principle:
$$ \text{Sum}(i, j, k, l) = PS[k][l] - PS[i-1][l] - PS[k][j-1] + PS[i-1][j-1] $$
Time: O(N²) for preprocessing; O(1) per query.
Space: O(N²) (to store the prefix sum matrix).
Solution code
import sys
def solve_submatrix_sum():
# Read N
try:
N = int(sys.stdin.readline())
except:
return
# Read i, j, k, l (r1, c1, r2, c2)
try:
coords = list(map(int, sys.stdin.readline().split()))
r1, c1, r2, c2 = coords[0], coords[1], coords[2], coords[3]
except:
return
# 1. Read and Store Matrix
matrix = []
for _ in range(N):
try:
row = list(map(int, sys.stdin.readline().split()))
matrix.append(row)
except:
return
# 2. Pre-calculate 2D Prefix Sum Array (O(N^2) Preprocessing)
# ps[i][j] stores the sum of sub-matrix from (0, 0) to (i-1, j-1)
ps = [[0] * (N + 1) for _ in range(N + 1)]
for i in range(1, N + 1):
for j in range(1, N + 1):
ps[i][j] = matrix[i-1][j-1] + ps[i-1][j] + ps[i][j-1] - ps[i-1][j-1]
# 3. Query the Submatrix Sum (O(1) Query)
# The query is for the region [r1, c1] to [r2, c2].
# Sum(r1, c1, r2, c2) = PS[r2+1][c2+1] - PS[r1][c2+1] - PS[r2+1][c1] + PS[r1][c1]
total_sum = (ps[r2 + 1][c2 + 1]
- ps[r1][c2 + 1]
- ps[r2 + 1][c1]
+ ps[r1][c1])
print(total_sum)
# Optional: Brute force approach for comparison (O(N^2) per query)
def submatrix_sum_brute(matrix, r1, c1, r2, c2):
sum_val = 0
for i in range(r1, r2 + 1):
for j in range(c1, c2 + 1):
sum_val += matrix[i][j]
return sum_val
if __name__ == "__main__":
solve_submatrix_sum()Other ways to solve it
- Thought of another approach (slower, or cleverer)? Code it here: the same tests check any approach.
Revising this one?
- →Solve it from memory before peeking
- →Say the pattern out loud, not just the code
- →Explain it like you would to a friend
- →Try it again in a different language