Find row and column pair in given Matrix with equal row and column sum
Last Updated :
07 Dec, 2022
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 sum
vector<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 Code
int 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 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<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 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.
Time Complexity: O(R*C)
Auxiliary Space: O(max(R, C))
Similar Reads
Find if a binary matrix exists with given row and column sums Given an array Row[] of size R where Row[i] is the sum of elements of the ith row and another array Column[] of size C where Column[i] is the sum of elements of the ith column. The task is to check if it is possible to construct a binary matrix of R * C dimension which satisfies given row sums and c
7 min read
Find Matrix With Given Row and Column Sums Given two arrays rowSum[] and colSum[] of size n and m respectively, the task is to construct a matrix of dimensions n à m such that the sum of matrix elements in every ith row is rowSum[i] and the sum of matrix elements in every jth column is colSum[j].Note: The resultant matrix can have only non-n
15 min read
Find a common element in all rows of a given row-wise sorted matrix Given a matrix where every row is sorted in increasing order. Write a function that finds and returns a common element in all rows. If there is no common element, then returns -1. Example: Input: mat[4][5] = { {1, 2, 3, 4, 5}, {2, 4, 5, 8, 10}, {3, 5, 7, 9, 11}, {1, 3, 5, 7, 9}, };Output: 5A O(m*n*n
15+ min read
Find a Square Matrix such that sum of elements in every row and column is K Given two integers N and K, the task is to find an N x N square matrix such that sum of every row and column should be equal to K. Note that there can be multiple such matrices possible. Print any one of them.Examples: Input: N = 3, K = 15 Output: 2 7 6 9 5 1 4 3 8Input: N = 3, K = 7 Output: 7 0 0 0
4 min read
Find sum of all elements in a matrix except the elements in row and/or column of given cell? Given a 2D matrix and a set of cell indexes e.g., an array of (i, j) where i indicates row and j column. For every given cell index (i, j), find sums of all matrix elements except the elements present in i'th row and/or j'th column. Example: mat[][] = { {1, 1, 2} {3, 4, 6} {5, 3, 2} } Array of Cell
12 min read
Largest square sub-matrix with equal row, column, and diagonal sum Given a matrix mat[][] of dimensions N*M, the task is to find the size of the largest square submatrix such that the sum of all rows, columns, diagonals in that submatrix are equal.Examples:Input: N = 3, M = 4, mat[][] = [[5, 1, 3, 1], [9, 3, 3, 1], [1, 3, 3, 8]]Output: 2Explanation:The submatrix wh
11 min read
Program to find the Sum of each Row and each Column of a Matrix Given a matrix mat of size m à n, the task is to compute the sum of each row and each column of the matrix.Examples:Input: mat = [ [1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16] ] Output: Sum of row 0 = 10 Sum of row 1 = 26 Sum of row 2 = 42 Sum of row 3 = 58 Sum of column 0 = 28 Sum
7 min read
Queries to count sum of rows and columns of a Matrix present in given ranges Given a matrix A[][] of size N * M and a 2D array queries[][] consisting of Q queries of the form {L, R}, the task is to count the number of row-sums and column-sums which are an integer from the range [L, R]. Examples: Input: N = 2, M = 2, A[][] = {{1, 4}, {2, 5}}, Q = 2, queries[][] = {{3, 7}, {3,
14 min read
Check if sums of i-th row and i-th column are same in matrix 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],[
5 min read
Count of cells equal to X in Matrix constructed as sum of rows and columns Given integer N denoting the size of a square matrix whose each element is the sum of its row and column i.e., mat[i][j] = i + j (0 < i, j, ⤠N), and an integer X, the task is to find how many cells have the value X. Examples: Input: N = 4, X = 2Output: 1Explanation: The matrix we get after using
7 min read