# 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:

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 ``using` `namespace` `std;` `// Function to return the pairs of``// rows and columns with equal sum``vector > equalPairs(vector >& M)``{``    ``vector > 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 Code``int` `main()``{``    ``vector > M{ { 1, 2, 2 },``                            ``{ 1, 5, 6 },``                            ``{ 3, 8, 9 } };` `    ``// Function call``    ``vector > 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 equalPairs(``int``[][] M)``    ``{``        ``List 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 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 sum``def` `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 Code``if` `__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 system``using` `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 equalPairs(``int``[,] M)``  ``{``    ``var` `ans = ``new` `List();``    ``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 sum``function` `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.`

Output
`{1, 1}`

Time Complexity: O(R*C)
Auxiliary Space: O(max(R, C))

Previous
Next