Matrix: Given a matrix, check if the sum of ith row and ith column are same

Problem Statement:

You are given a 2D matrix of size m * n, you need to check if the sum of ith row and ith column are same.

If the dimension is 4 * 6, then check for only first 4 rows and columns.

Example:

Input:

1, 2
2, 1

The sum of 1st row is 3 and first column is 3.

Similarly 2nd row is 3 and second column is 3.

Output:

True

Solution Explanation:

For the solution, we need to check the sum of each row matches the sum of the corresponding column.

Then iterate through the first min(n,m) rows and columns.

Time Complexity: O(n * m)
Space Complexity: O(1)

Code Solution

#include <iostream>
#include <vector>
using namespace std;

const int MAX = 100;


bool solution(vector<vector<int>> &mat) {

    int n = mat.size();      
    int m = mat[0].size(); 

    int range = min(n, m);   

    for (int i = 0; i < range; i++) {

        int rowSum = 0, colSum = 0;

        for (int j = 0; j < m; j++) {
            rowSum += mat[i][j];
        }

        for (int j = 0; j < n; j++) {
            colSum += mat[j][i];
        }

        if (rowSum != colSum) {
            return false;
        }
    }

    return true; 
}

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

    cout << (solution(mat) ? "True" : "False") << endl;

    return 0;
}

Output

True
Write a Comment

Leave a Comment

Your email address will not be published. Required fields are marked *