Open In App

Check if sums of i-th row and i-th column are same in matrix

Last Updated : 17 Feb, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Given a matrix mat[][] of dimensions n*m, we have to check if the sum of i-th row is equal to the sum of i-th column or not. 
Note: Check only up to valid row and column numbers i.e. if the dimensions are 3x5, check only for the first 3 rows and columns, i.e. min(n, m).

Examples: 

Input: mat = [[1,2],[2,1]]
Output: 1
Explanation: The sum of 1st row is equal to sum of1st column and also sum of 2nd row is equal to the sum of 2nd column. So, Answer is 1.

Input: mat = [[5],[0],[0]]
Output: 1
Explanation: The sum of 1st column is equal to the sum of 1st row.Thus,answer is 1. (We do not check for the 2nd and 3rd rows because there are no 2nd and 3rd columns.)

Approach:

The idea is to check whether the sum of each row matches the sum of the corresponding column within the valid range of the matrix.

  • We iterate through the first min(n, m) rows and columns, computing their sums separately.
  • If any row sum differs from the corresponding column sum, we return false; otherwise, we return true.
C++
// C++ implementation to check if the sum of each row 
// is equal to the sum of the corresponding column 
#include <bits/stdc++.h>
using namespace std;

bool isRowColumnEqual(vector<vector<int>> &mat) {
    int n = mat.size();      
    int m = mat[0].size(); 
    // Valid range to check
    int limit = min(n, m);   

    for (int i = 0; i < limit; i++) {
        int rowSum = 0, colSum = 0;

        // Calculate sum of the i-th row
        for (int j = 0; j < m; j++) {
            rowSum += mat[i][j];
        }

        // Calculate sum of the i-th column
        for (int j = 0; j < n; j++) {
            colSum += mat[j][i];
        }

        // If any row sum != column sum, return false
        if (rowSum != colSum) {
            return false;
        }
    }

    return true; 
}

int main() {
    vector<vector<int>> mat = {{1, 2}, {2, 1}};

    cout << (isRowColumnEqual(mat) ? "1" : "0") << endl;

    return 0;
}
Java
// Java implementation to check if the sum of each row
// is equal to the sum of the corresponding column

import java.util.*;

class GfG {
    
    static boolean isRowColumnEqual(List<List<Integer>> mat) {
        int n = mat.size();        
        int m = mat.get(0).size(); 
        // Valid range to check
        int limit = Math.min(n, m); 

        for (int i = 0; i < limit; i++) {
            int rowSum = 0, colSum = 0;

            // Calculate sum of the i-th row
            for (int j = 0; j < m; j++) {
                rowSum += mat.get(i).get(j);
            }

            // Calculate sum of the i-th column
            for (int j = 0; j < n; j++) {
                colSum += mat.get(j).get(i);
            }

            // If any row sum != column sum, return false
            if (rowSum != colSum) {
                return false;
            }
        }
        return true; 
    }

    public static void main(String[] args) {
        List<List<Integer>> mat = Arrays.asList(
            Arrays.asList(1, 2),
            Arrays.asList(2, 1)
        );

        System.out.println(isRowColumnEqual(mat) ? "1" : "0");
    }
}
Python
# Python implementation to check if the sum of each row
# is equal to the sum of the corresponding column

def is_row_column_equal(mat):
    n = len(mat)       
    m = len(mat[0]) 
    # Valid range to check
    limit = min(n, m)  

    for i in range(limit):
        row_sum = sum(mat[i])  # Sum of the i-th row
        col_sum = sum(mat[j][i] for j in range(n))  # Sum of the i-th column

        # If any row sum != column sum, return False
        if row_sum != col_sum:
            return False

    return True  

if __name__ == "__main__":
    mat = [[1, 2], [2, 1]]
    print("1" if is_row_column_equal(mat) else "0")
C#
// C# implementation to check if the sum of each row
// is equal to the sum of the corresponding column
using System;
using System.Collections.Generic;

class GfG {
    
    public static bool IsRowColumnEqual(List<List<int>> mat) {
        int n = mat.Count;         
        int m = mat[0].Count;  
        // Valid range to check
        int limit = Math.Min(n, m); 

        for (int i = 0; i < limit; i++) {
            int rowSum = 0, colSum = 0;

            // Calculate sum of the i-th row
            for (int j = 0; j < m; j++) {
                rowSum += mat[i][j];
            }

            // Calculate sum of the i-th column
            for (int j = 0; j < n; j++) {
                colSum += mat[j][i];
            }

            // If any row sum != column sum, return false
            if (rowSum != colSum) {
                return false;
            }
        }
        return true; 
    }

    public static void Main() {
        List<List<int>> mat = new List<List<int>> {
            new List<int> {1, 2},
            new List<int> {2, 1}
        };

        Console.WriteLine(IsRowColumnEqual(mat) ? "1" : "0");
    }
}
JavaScript
// JavaScript implementation to check if the sum of each row
// is equal to the sum of the corresponding column

function isRowColumnEqual(mat) {
    let n = mat.length;       
    let m = mat[0].length;    
    // Valid range to check
    let limit = Math.min(n, m); 

    for (let i = 0; i < limit; i++) {
        // Sum of the i-th row
        let rowSum = mat[i].reduce((sum, num) => sum + num, 0); 
        let colSum = 0;

        // Calculate sum of the i-th column
        for (let j = 0; j < n; j++) {
            colSum += mat[j][i];
        }

        // If any row sum != column sum, return false
        if (rowSum !== colSum) {
            return false;
        }
    }
    return true; 
}


let mat = [[1, 2], [2, 1]];
console.log(isRowColumnEqual(mat) ? "1" : "0");

Output
1

Time Complexity: O(n * m) since we iterate through all valid rows and columns to compute their sums.
Auxiliary Space: O(1), since no extra space has been taken.
 


Article Tags :
Practice Tags :

Similar Reads