Find row and column pair in given Matrix with equal row and column sum

Given a matrix Mat of size N x M, the task is to find all the pairs of rows and columns where the sum of elements in the row is equal to the sum of elements in the columns.
Examples:
Input: M = {{1, 2, 2}, {1, 5, 6}, {3, 8, 9}}
Output: {{1, 1}}
Explanation: The sum of elements of rows and columns of matrix M are:
 C = 1 C = 2 C = 3 Sum of Rows R = 1 1 2 2 5 R = 2 1 5 6 12 R = 3 3 8 9 20 Sum of Columns 5 15 17  Thus, row 1 and columns 1 has same sum.
Input: M = {{1, 2, 3, 4}, {2, 5, 8, 7}, {3, 8, 9, 3}, {0, 6, 3, 2}}
Output: {{3, 3}}
Approach: To solve the problem follow the below idea:
The idea is to calculate the sum of each row and store them in an array, do the same for each column. Compare values from these arrays and return the result.
Follow the steps to solve this problem:
- Declare to arrays, arrR[] to store the sums of each row, and arrC[] to store the sums of each column.
- Using nested loops calculate the sums of each row and store the values in arrR[].
- Using nested loops calculate the sums of each column and store the values in arrC[].
- Use the nested loops to check if for any pair of rows and columns the sums are equal and store them if possible.
Below is the implementation of this approach:
C++
// C++ code to implement this approach#include <bits/stdc++.h>using namespace std;Â
// Function to return the pairs of// rows and columns with equal sumvector<pair<int, int> > equalPairs(vector<vector<int> >& M){Â Â Â Â vector<pair<int, int> > ans;Â Â Â Â int R = M.size(), C = M[0].size();Â Â Â Â vector<int> arrR(R), arrC(C);Â
    // Calculate the sum of each row    for (int i = 0; i < R; ++i) {        int s = 0;        for (int j = 0; j < C; ++j)            s += M[i][j];        arrR[i] = s;    }Â
    // Calculate the sum of each column    for (int j = 0; j < C; ++j) {        int s = 0;        for (int i = 0; i < R; ++i)            s += M[i][j];        arrC[j] = s;    }Â
    // Check whether any pair of row and    // column have equal sum of elements    for (int i = 0; i < R; ++i) {        for (int j = i; j < C; ++j) {            if (arrR[i] == arrC[j])                ans.push_back({ i + 1, j + 1 });        }    }    return ans;}Â
// Driver Codeint main(){    vector<vector<int> > M{ { 1, 2, 2 },                            { 1, 5, 6 },                            { 3, 8, 9 } };Â
    // Function call    vector<pair<int, int> > ans = equalPairs(M);    if (ans.size() == 0)        cout << "No such pairs exists";    else {        for (int i = 0; i < ans.size(); i++)            cout << "{" << ans[i].first << ", "                 << ans[i].second << "}\n";    }    return 0;} |
Java
// Java code for the above approachÂ
import java.io.*;import java.util.*;Â
class GFG {Â
    static class pair {        int first, second;        public pair(int first, int second)        {            this.first = first;            this.second = second;        }    }Â
    // Function to return the pairs of rows and columns with    // equal sum    static List<pair> equalPairs(int[][] M)    {        List<pair> ans = new ArrayList<>();        int R = M.length, C = M[0].length;        int[] arrR = new int[R];        int[] arrC = new int[C];Â
        // Calculate the sum of each row        for (int i = 0; i < R; ++i) {            int s = 0;            for (int j = 0; j < C; ++j)                s += M[i][j];            arrR[i] = s;        }Â
        // Calculate the sum of each column        for (int j = 0; j < C; ++j) {            int s = 0;            for (int i = 0; i < R; ++i)                s += M[i][j];            arrC[j] = s;        }Â
        // Check whether any pair of row and        // column have equal sum of elements        for (int i = 0; i < R; ++i) {            for (int j = i; j < C; ++j) {                if (arrR[i] == arrC[j])                    ans.add(new pair(i + 1, j + 1));            }        }        return ans;    }Â
    public static void main(String[] args)    {        int[][] M = new int[][] { { 1, 2, 2 },                                  { 1, 5, 6 },                                  { 3, 8, 9 } };Â
        // Function call        List<pair> ans = equalPairs(M);        if (ans.size() == 0) {            System.out.print("No such pairs exists");        }        else {            for (int i = 0; i < ans.size(); i++) {                pair temp = (pair)ans.get(i);                System.out.println("{" + temp.first + ","                                   + temp.second + "}");            }        }    }}Â
// This code is contributed by lokeshmvs21. |
Python3
# Python code to implement this approachÂ
# Function to return the pairs of# rows and columns with equal sumdef equalPairs(M):Â Â Â Â ans = []Â Â Â Â R = len(M)Â Â Â Â C = len(M[0])Â Â Â Â arrR = [0] * RÂ Â Â Â arrC = [0] * CÂ
    # Calculate the sum of each row    for i in range(R):        s = 0        for j in range(C):            s += M[i][j]        arrR[i] = sÂ
    # Calculate the sum of each column    for j in range(C):        s = 0        for i in range(R):            s += M[i][j]        arrC[j] = sÂ
    # Check whether any pair of row and    # column have equal sum of elements    for i in range(R):        for j in range(i, C):            if arrR[i] == arrC[j]:                ans.append((i + 1, j + 1))Â
    return ansÂ
# Driver Codeif __name__ == '__main__':Â Â Â Â M = [[1, 2, 2], [1, 5, 6], [3, 8, 9]]Â
    # Function call    ans = equalPairs(M)Â
    if len(ans) == 0:        print("No such pairs exists")Â
    else:        for i in range(len(ans)):            print("{", ans[i][0], ", ", ans[i][1], "}", sep="")Â
# This code is contributed by Tapesh(tapeshdua420) |
C#
// Include namespace systemusing System;using System.Collections.Generic;Â
using System.Linq;using System.Collections;Â
public class GFG{  class pair  {    public int first;    public int second;    public pair(int first, int second)    {      this.first = first;      this.second = second;    }  }  // Function to return the pairs of rows and columns with  // equal sum  static List<pair> equalPairs(int[,] M)  {    var ans = new List<pair>();    var R = M.GetLength(0);    var C = M.GetLength(1);    int[] arrR = new int[R];    int[] arrC = new int[C];    // Calculate the sum of each row    for (int i = 0; i < R; ++i)    {      var s = 0;      for (int j = 0; j < C; ++j)      {        s += M[i,j];      }      arrR[i] = s;    }    // Calculate the sum of each column    for (int j = 0; j < C; ++j)    {      var s = 0;      for (int i = 0; i < R; ++i)      {        s += M[i,j];      }      arrC[j] = s;    }    // Check whether any pair of row and    // column have equal sum of elements    for (int i = 0; i < R; ++i)    {      for (int j = i; j < C; ++j)      {        if (arrR[i] == arrC[j])        {          ans.Add(new pair(i + 1, j + 1));        }      }    }    return ans;  }  public static void Main(String[] args)  {    int[,] M = {{1, 2, 2}, {1, 5, 6}, {3, 8, 9}};Â
    // Function call    var ans = GFG.equalPairs(M);    if (ans.Count == 0)    {      Console.Write("No such pairs exists");    }    else    {      for (int i = 0; i < ans.Count; i++)      {        var temp = (pair)ans[i];        Console.WriteLine("{" + temp.first.ToString() + "," + temp.second.ToString() + "}");      }    }  }}Â
// This code is contributed by aadityaburujwale. |
Javascript
// Javascript code to implement this approachÂ
// Function to return the pairs of// rows and columns with equal sumfunction equalPairs(M){Â Â Â Â let ans=[];Â Â Â Â let R = M.length, C = M[0].length;Â Â Â Â arrR=new Array(R).fill(0);Â Â Â Â arrC=new Array(C).fill(0);Â
    // Calculate the sum of each row    for (let i = 0; i < R; ++i) {        let s = 0;        for (let j = 0; j < C; ++j)            s += M[i][j];        arrR[i] = s;    }Â
    // Calculate the sum of each column    for (let j = 0; j < C; ++j) {        let s = 0;        for (let i = 0; i < R; ++i)            s += M[i][j];        arrC[j] = s;    }Â
    // Check whether any pair of row and    // column have equal sum of elements    for (let i = 0; i < R; ++i) {        for (let j = i; j < C; ++j) {            if (arrR[i] == arrC[j])                ans.push([ i + 1, j + 1 ]);        }    }    return ans;}Â
// Driver Code    let M = [[ 1, 2, 2 ],[ 1, 5, 6 ],[ 3, 8, 9 ] ];Â
    // Function call    let ans = equalPairs(M);    if (ans.length == 0)        console.log("No such pairs exists");    else {        for (let i = 0; i < ans.length; i++)            console.log("{"+ans[i][0]+", "+ans[i][1]+"}");    }         // This code is contributed by Pushpesh Raj. |
{1, 1}
Time Complexity: O(R*C)
Auxiliary Space: O(max(R, C))
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 zambiatek!



