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

We have a 2D matrix and a set of cell indices represented as (i, j) where i is the row and j is the column. For each given cell index, we need to find the sum of all matrix elements excluding the elements in the ith row and jth column.

For example, if we have the matrix:

2 2 3
4 5 7
6 4 3

And cell indices = [(0, 0), (1, 1), (0, 1)], the output will be [19, 14, 20].

Algorithm

To solve this problem, we follow these steps:

  • For each cell index (row, col) in the input array
  • Iterate through all elements in the matrix
  • Add elements to the sum only if they are not in the specified row and not in the specified column
  • Store the sum and repeat for the next cell index

Implementation

Here's the complete Python implementation ?

def show_sums(mat, ind_arr):
    n = len(ind_arr)
    ans = []
    
    for i in range(n):
        total = 0
        row = ind_arr[i][0]
        col = ind_arr[i][1]
        
        # Iterate through all matrix elements
        for j in range(len(mat)):
            for k in range(len(mat[0])):
                # Add element if it's not in the excluded row or column
                if j != row and k != col:
                    total += mat[j][k]
        
        ans.append(total)
    
    return ans

# Test the function
mat = [[2, 2, 3], [4, 5, 7], [6, 4, 3]]
ind_arr = [(0, 0), (1, 1), (0, 1)]
result = show_sums(mat, ind_arr)
print(result)

The output of the above code is ?

[19, 14, 20]

How It Works

Let's trace through the first cell index (0, 0):

  • We exclude row 0: [2, 2, 3]
  • We exclude column 0: [2, 4, 6]
  • Remaining elements: 5, 7, 4, 3
  • Sum: 5 + 7 + 4 + 3 = 19

For cell index (1, 1):

  • We exclude row 1: [4, 5, 7]
  • We exclude column 1: [2, 5, 4]
  • Remaining elements: 2, 3, 6, 3
  • Sum: 2 + 3 + 6 + 3 = 14

Optimized Approach

For better performance with large matrices, we can pre-calculate totals ?

def show_sums_optimized(mat, ind_arr):
    rows = len(mat)
    cols = len(mat[0])
    
    # Calculate total sum
    total_sum = sum(sum(row) for row in mat)
    
    # Calculate row sums and column sums
    row_sums = [sum(mat[i]) for i in range(rows)]
    col_sums = [sum(mat[i][j] for i in range(rows)) for j in range(cols)]
    
    ans = []
    for row, col in ind_arr:
        # Total - row_sum - col_sum + intersection (double subtracted)
        result = total_sum - row_sums[row] - col_sums[col] + mat[row][col]
        ans.append(result)
    
    return ans

# Test the optimized function
mat = [[2, 2, 3], [4, 5, 7], [6, 4, 3]]
ind_arr = [(0, 0), (1, 1), (0, 1)]
result = show_sums_optimized(mat, ind_arr)
print(result)

The output is ?

[19, 14, 20]

Comparison

Method Time Complexity Space Complexity Best For
Basic Approach O(n × m × k) O(1) Small matrices
Optimized Approach O(n × m + k) O(n + m) Large matrices, multiple queries

Where n = rows, m = columns, k = number of cell indices.

Conclusion

The basic approach iterates through all elements for each query, while the optimized approach pre-calculates sums for better performance. Use the optimized version when dealing with large matrices or multiple queries.

Updated on: 2026-03-25T09:25:33+05:30

986 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements