VOOZH about

URL: https://www.geeksforgeeks.org/dsa/find-sum-of-all-elements-in-a-matrix-except-the-elements-in-given-row-andor-column-2/

⇱ Find sum of all elements in a matrix except the elements in row and/or column of given cell? - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Find sum of all elements in a matrix except the elements in row and/or column of given cell?

Last Updated : 6 Oct, 2023

Given a 2D matrix and a set of cell indexes e.g., an array of (i, j) where i indicates row and j column. For every given cell index (i, j), find sums of all matrix elements except the elements present in i'th row and/or j'th column.

Example: 

mat[][] = { {1, 1, 2}
 {3, 4, 6}
 {5, 3, 2} }
Array of Cell Indexes: {(0, 0), (1, 1), (0, 1)}
Output: 15, 10, 16

A Naive Solution is to one by once consider all given cell indexes. For every cell index (i, j), find the sum of matrix elements that are not present either at i'th row or at j'th column.

Implementation:


Output
15
10
16

Time Complexity of the above solution is O(n * R * C) where n is number of given cell indexes and R x C is matrix size. 
Auxiliary Space: O(1)


An Efficient Solution can compute all sums in O(R x C + n) time. The idea is to precompute total sum, row and column sums before processing the given array of indexes.

  1. Calculate sum of matrix, call it sum. 
  2. Calculate sum of individual rows and columns. (row[] and col[]) 
  3. For a cell index (i, j), the desired sum will be "sum- row[i] - col[j] + arr[i][j]"

Below is the implementation of above idea.


Output
15
10
16

Time Complexity: O(R x C + n) 
Auxiliary Space: O(R + C)

Thanks to Gaurav Ahirwar for suggesting this efficient solution.

Comment
Article Tags:
Article Tags: