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 Hash
  • Practice Hash
  • MCQs on Hash
  • Hashing Tutorial
  • Hash Function
  • Index Mapping
  • Collision Resolution
  • Open Addressing
  • Separate Chaining
  • Quadratic probing
  • Double Hashing
  • Load Factor and Rehashing
  • Advantage & Disadvantage
Open In App
Next Article:
Find distinct elements common to all rows of a matrix
Next article icon

Common elements in all rows of a given matrix

Last Updated : 07 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Given an m x n matrix, find all common elements present in all rows in O(mn) time and one traversal of matrix.

Example: 

Input:
mat[4][5] = {{1, 2, 1, 4, 8},
{3, 7, 8, 5, 1},
{8, 7, 7, 3, 1},
{8, 1, 2, 7, 9},
};

Output:
1 8 or 8 1
8 and 1 are present in all rows.

A simple solution is to consider every element and check if it is present in all rows. If present, then print it. 
A better solution is to sort all rows in the matrix and use similar approach as discussed here. Sorting will take O(mnlogn) time and finding common elements will take O(mn) time. So overall time complexity of this solution is O(mnlogn)

Can we do better than O(mnlogn)? 
The idea is to use maps. We initially insert all elements of the first row in an map. For every other element in remaining rows, we check if it is present in the map. If it is present in the map and is not duplicated in current row, we increment count of the element in map by 1, else we ignore the element. If the currently traversed row is the last row, we print the element if it has appeared m-1 times before. 

Below is the implementation of the idea:

C++
// A Program to prints common element in all // rows of matrix #include <bits/stdc++.h> using namespace std;  // Specify number of rows and columns #define M 4 #define N 5  // prints common element in all rows of matrix void printCommonElements(int mat[M][N]) {     unordered_map<int, int> mp;      // initialize 1st row elements with value 1     for (int j = 0; j < N; j++)         mp[(mat[0][j])] = 1;      // traverse the matrix     for (int i = 1; i < M; i++)     {         for (int j = 0; j < N; j++)         {             // If element is present in the map and             // is not duplicated in current row.             if (mp[(mat[i][j])] == i)             {                // we increment count of the element                // in map by 1                 mp[(mat[i][j])] = i + 1;                  // If this is last row                 if (i==M-1 && mp[(mat[i][j])]==M)                   cout << mat[i][j] << " ";             }         }     } }  // driver program to test above function int main() {     int mat[M][N] =     {         {1, 2, 1, 4, 8},         {3, 7, 8, 5, 1},         {8, 7, 7, 3, 1},         {8, 1, 2, 7, 9},     };      printCommonElements(mat);      return 0; } 
Java
// Java Program to prints common element in all // rows of matrix import java.util.*;  class GFG  {  // Specify number of rows and columns static int M = 4; static int N =5;  // prints common element in all rows of matrix static void printCommonElements(int mat[][]) {      Map<Integer,Integer> mp = new HashMap<>();          // initialize 1st row elements with value 1     for (int j = 0; j < N; j++)         mp.put(mat[0][j],1);              // traverse the matrix     for (int i = 1; i < M; i++)     {         for (int j = 0; j < N; j++)         {             // If element is present in the map and             // is not duplicated in current row.             if (mp.get(mat[i][j]) != null && mp.get(mat[i][j]) == i)             {                 // we increment count of the element                 // in map by 1                 mp.put(mat[i][j], i + 1);                  // If this is last row                 if (i == M - 1)                     System.out.print(mat[i][j] + " ");             }         }     } }  // Driver code public static void main(String[] args)  {     int mat[][] =     {         {1, 2, 1, 4, 8},         {3, 7, 8, 5, 1},         {8, 7, 7, 3, 1},         {8, 1, 2, 7, 9},     };      printCommonElements(mat); } }  // This code contributed by Rajput-Ji 
Python3
# A Program to prints common element  # in all rows of matrix  # Specify number of rows and columns M = 4 N = 5  # prints common element in all  # rows of matrix def printCommonElements(mat):      mp = dict()      # initialize 1st row elements      # with value 1     for j in range(N):         mp[(mat[0][j])] = 1      # traverse the matrix     for i in range(1, M):         for j in range(N):                          # If element is present in the             # map and is not duplicated in              # current row.             if (mat[i][j] in mp.keys() and                              mp[(mat[i][j])] == i):                                               # we increment count of the              # element in map by 1                 mp[(mat[i][j])] = i + 1                  # If this is last row                 if i == M - 1:                     print(mat[i][j], end = " ")              # Driver Code mat = [[1, 2, 1, 4, 8],        [3, 7, 8, 5, 1],        [8, 7, 7, 3, 1],        [8, 1, 2, 7, 9]]  printCommonElements(mat)  # This code is contributed  # by mohit kumar 29 
C#
// C# Program to print common element in all // rows of matrix to another. using System;  using System.Collections.Generic;   class GFG  {  // Specify number of rows and columns static int M = 4; static int N = 5;  // prints common element in all rows of matrix static void printCommonElements(int [,]mat) {      Dictionary<int, int> mp = new Dictionary<int, int>();          // initialize 1st row elements with value 1     for (int j = 0; j < N; j++)     {         if(!mp.ContainsKey(mat[0, j]))             mp.Add(mat[0, j], 1);     }          // traverse the matrix     for (int i = 1; i < M; i++)     {         for (int j = 0; j < N; j++)         {             // If element is present in the map and             // is not duplicated in current row.             if (mp.ContainsKey(mat[i, j])&&                (mp[(mat[i, j])] != 0 &&                  mp[(mat[i, j])] == i))             {                 // we increment count of the element                 // in map by 1                 if(mp.ContainsKey(mat[i, j]))                 {                     var v = mp[(mat[i, j])];                     mp.Remove(mat[i, j]);                     mp.Add(mat[i, j], i + 1);                 }                 else                     mp.Add(mat[i, j], i + 1);                  // If this is last row                 if (i == M - 1)                     Console.Write(mat[i, j] + " ");             }         }     } }  // Driver code public static void Main(String[] args)  {     int [,]mat = {{1, 2, 1, 4, 8},                   {3, 7, 8, 5, 1},                   {8, 7, 7, 3, 1},                   {8, 1, 2, 7, 9}};      printCommonElements(mat); } }  // This code is contributed by 29AjayKumar 
JavaScript
<script> // Javascript Program to prints common element in all // rows of matrix          // Specify number of rows and columns     let M = 4;     let N =5;          // prints common element in all rows of matrix     function printCommonElements(mat)     {         let mp = new Map();           // initialize 1st row elements with value 1     for (let j = 0; j < N; j++)         mp.set(mat[0][j],1);               // traverse the matrix     for (let i = 1; i < M; i++)     {         for (let j = 0; j < N; j++)         {             // If element is present in the map and             // is not duplicated in current row.             if (mp.get(mat[i][j]) != null && mp.get(mat[i][j]) == i)             {                 // we increment count of the element                 // in map by 1                 mp.set(mat[i][j], i + 1);                   // If this is last row                 if (i == M - 1)                     document.write(mat[i][j] + " ");             }         }     }     }          // Driver code     let mat = [[1, 2, 1, 4, 8],        [3, 7, 8, 5, 1],        [8, 7, 7, 3, 1],        [8, 1, 2, 7, 9]]        printCommonElements(mat)          // This code is contributed by unknown2108 </script> 

Output
8 1 

The time complexity of this solution is O(m * n) and we are doing only one traversal of the matrix.
Auxiliary Space: O(N)




Next Article
Find distinct elements common to all rows of a matrix

A

Aarti_Rathi and Aditya Goel
Improve
Article Tags :
  • DSA
  • Hash
  • Matrix
Practice Tags :
  • Hash
  • Matrix

Similar Reads

  • Find distinct elements common to all rows of a matrix
    Given a n x n matrix. The problem is to find all the distinct elements common to all rows of the matrix. The elements can be printed in any order. Examples: Input : mat[][] = { {2, 1, 4, 3}, {1, 2, 3, 2}, {3, 6, 2, 3}, {5, 2, 5, 3} } Output : 2 3 Input : mat[][] = { {12, 1, 14, 3, 16}, {14, 2, 1, 3,
    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
  • Making all elements of matrix equal to a given element K
    Given a 2-d array arr[][], the task is to check whether it is possible to make all elements of the array to equal to a given number k if, in one operation, any element can be chosen and the surrounding diagonal elements can be made equal to it. Examples: Input: arr[][] = 1 8 3 1 2 2 4 1 9k = 2Output
    7 min read
  • Count of unique rows in a given Matrix
    Given a 2D matrix arr of size N*M containing lowercase English letters, the task is to find the number of unique rows in the given matrix. Examples: Input: arr[][]= { {'a', 'b', 'c', 'd'}, {'a', 'e', 'f', 'r'}, {'a', 'b', 'c', 'd'}, {'z', 'c', 'e', 'f'} }Output: 2Explanation: The 2nd and the 4th row
    10 min read
  • Find maximum element of each row in a matrix
    Given a matrix mat[][], the task is to find the maximum element of each row. Examples: Input: mat[][] = [[1, 2, 3] [1, 4, 9] [76, 34, 21]]Output :3976Input: mat[][] = [[1, 2, 3, 21] [12, 1, 65, 9] [1, 56, 34, 2]]Output :216556 The idea is to run the loop for no_of_rows. Check each element inside the
    4 min read
  • Sum of all even frequency elements in Matrix
    Given a NxM matrix of integers containing duplicate elements. The task is to find the sum of all even occurring elements in the given matrix. That is the sum of all such elements whose frequency is even in the matrix. Examples: Input : mat[] = {{1, 1, 2}, {2, 3, 3}, {4, 5, 3}} Output : 18 The even o
    5 min read
  • All adjacent of a given element in a 2D Array or Matrix
    Given a 2d integer array arr, your task is to return all the adjacent elements of a particular integer whose position is given as (x, y).Note: Adjacent elements are all the elements that share a common side or point i.e., they have a vertical, horizontal or diagonal distance of 1. Examples: Input: a
    12 min read
  • Count rows in a matrix that consist of same element
    Given a matrix mat[][], the task is to count the number of rows in the matrix that consists of the same elements. Examples: Input: mat[][] = {{1, 1, 1}, {1, 2, 3}, {5, 5, 5}} Output: 2 All the elements of the first row and all the elements of the third row are the same. Input: mat[][] = {{1, 2}, {4,
    9 min read
  • Row-wise common elements in two diagonals of a square matrix
    Given a square matrix, find out count of numbers that are same in same row and same in both primary and secondary diagonals. Examples : Input : 1 2 1 4 5 2 0 5 1 Output : 2 Primary diagonal is 1 5 1 Secondary diagonal is 1 5 0 Two elements (1 and 5) match in two diagonals and same. Input : 1 0 0 0 1
    4 min read
  • Minimum element of each row and each column in a matrix
    Given a matrix, the task is to find the minimum element of each row and each column. Examples: Input: [1, 2, 3] [1, 4, 9] [76, 34, 21] Output: Minimum element of each row is {1, 1, 21} Minimum element of each column is {1, 2, 3} Input: [1, 2, 3, 21] [12, 1, 65, 9] [11, 56, 34, 2] Output: Minimum ele
    11 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