Last Updated: 3 Jan, 2026

Matrix Block Sum

Easy
Asked in company
BrowserStack

Problem statement

You are given a 2D integer matrix (an array of arrays). Your task is to efficiently calculate the sum of elements within a specific rectangular block of this matrix.


The rectangular block is defined by its top-left corner at (r1, c1) and its bottom-right corner at (r2, c2). You need to find the sum of all elements matrix[i][j] such that r1 <= i <= r2 and c1 <= j <= c2.


Input Format:
The first line contains two space-separated integers: R (number of rows) and C (number of columns) in the matrix.

The next R lines each contain C space-separated integers, representing the rows of the matrix.

The final line contains four space-separated integers: r1, c1, r2, c2, representing the 0-indexed coordinates of the top-left and bottom-right corners of the target rectangle.


Output Format:
The output should be a single integer representing the sum of all elements within the specified rectangle.


Note:
The matrix coordinates are 0-indexed.

The rectangle's boundaries (r1, c1, r2, c2) are inclusive.

The sum can be large, so be mindful of potential integer overflow.