Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Problems on Matrix
  • Practice Matrix
  • MCQs on Matrix
  • Tutorial on Matrix
  • Matrix Traversal
  • Sorting in Matrix
  • Matrix Rotation
  • Transpose of Matrix
  • Inverse of Matrix
  • Determinant of Matrix
  • Matrix Application
  • Adjoint & Inverse Matrix
  • Sparse Matrix
  • Matrix Exponentiation
Open In App
Next Article:
Find if a binary matrix exists with given row and column sums
Next article icon

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

Last Updated : 07 Dec, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

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 = 1C = 2C = 3Sum of Rows
R = 11225
R = 215612
R = 338920
Sum of Columns51517 

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.      

Output
{1, 1}

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


Next Article
Find if a binary matrix exists with given row and column sums
author
aditya942003patil
Improve
Article Tags :
  • Matrix
  • DSA
Practice Tags :
  • Matrix

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-
    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
    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 Su
    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
  • Enlarge a Matrix such that each element occurs in R rows and C columns
    Given a matrix arr[][] of size N x M, and two numbers R and C, the task is to enlarge this matrix such that each element of the original matrix occurs in R rows and C columns in the enlarged matrix. Examples: Input: arr[][] = {{1, 2, 3}, {4, 5, 6}} R = 3, C = 2 Output: 1 1 2 2 3 3 4 4 5 5 6 6 1 1 2
    9 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
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences