VOOZH about

URL: https://www.geeksforgeeks.org/dsa/print-cells-rectangular-sum-matrix/

⇱ Print cells with same rectangular sums in a matrix - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Print cells with same rectangular sums in a matrix

Last Updated : 23 Jul, 2025

Given a matrix of m x n matrix, we need to print all those cells at which sum of sub-matrix ended at this cell and sub-matrix starting at this cell is equal to remaining elements. For better understanding please see below diagram,

Examples : 

Input : mat[][] = {1, 2, 3, 5,
 4, 1, 0, 2,
 0, 1, 2, 0,
 7, 1, 1, 0};
Output : (1, 1), (2, 2) 

In above matrix, cell (1, 1) and cell (2, 2)
are our required cells because,
For cell (1, 1), sum of red and green areas is same
1+2+4+1+0+2+1+2+0+1+1+0 = 3+5+0+7 
Same is true for cell (2, 2)
1+2+3+4+1+0+0+1+2+0+1+0 = 5+2+7+1 

We need to print all blue boundary cells for 
which sum of red area is equal to green area.

👁 Image

First we construct auxiliary sub-matrices similar to the linked article.

We construct two matrices sum[][] and sumr[][] such that sum[i][j] denotes sum of sub-matrix from mat[0][0] to mat[i][j]. And sumr for storing sum till last indices i.e. sumr[i][j] denotes sum of sub-matrix, mat[i][j] to mat[m - 1][n - 1]. 

Now we can use above matrices for solving this problem, red area shown in above diagram can be calculated by adding corresponding cells from sum and sumr matrices, as mat[i][j] is considered twice while calculating this sum we will subtract it once to get sum of red area. Getting sum of remaining element, the green part, is pretty easy, we will just subtract sum of red part from total sum of given matrix. 

So to check whether a particular cell satisfies the given condition we will calculate the sum of red part as explained above and compare it with total sum of matrix, if this sum is half of total sum, current cell satisfies the condition and hence a candidate for result.

Implementation:


Output
(1, 1)
(2, 2)

Time complexity: O(n x m).
Auxiliary Space: O(n x m).

Comment
Article Tags:
Article Tags: