Skip to content

Commit 2bd21fc

Browse files
Checking the common elements in a row of a matrix
1 parent 3810c17 commit 2bd21fc

File tree

1 file changed

+62
-0
lines changed

1 file changed

+62
-0
lines changed
Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
/******************************************************************************
2+
3+
Given an m x n matrix, find all common elements present in all rows in one traversal of matrix.
4+
5+
*******************************************************************************/
6+
7+
//SOLUTION (in C++)
8+
9+
#include <bits/stdc++.h>
10+
11+
using namespace std;
12+
#define M 4
13+
#define N 5
14+
15+
16+
void printCommonElements(int arr[M][N])
17+
{
18+
int i, j;
19+
//we'll use a amp to store the count of common numbers in a rows
20+
unordered_map<int, int> m;
21+
22+
//since, we need to find common elements, it is completely dependent on the first row of the Matrix
23+
//initially all the 1st row elements count will be 1, even if they contain duplicates
24+
for(i = 0;i<N;i++)
25+
m[arr[0][i]] = 1;
26+
27+
//traverse the matrix
28+
for(i = 1;i<M;i++)
29+
{
30+
for(j = 0;j<N;j++)
31+
{
32+
33+
//for any row, my element's freq should be equal to the previous row's number,
34+
//if it is, then there is high chance that it can be common and we;'' increase the count.
35+
//we are ignoring the elements whose gfreq count is not equal to the row, so it reduces our work
36+
if(m[arr[i][j]] == i){
37+
m[arr[i][j]]++;
38+
39+
//if the freq of the element in the row becomes equal to the no. of rows,
40+
//then it means it is coming in all rows and is the common element.
41+
if(m[arr[i][j]] == M){
42+
cout<<arr[i][j]<<" ";
43+
}
44+
}
45+
}
46+
}
47+
}
48+
49+
int main()
50+
{
51+
cout<<"Matrix"<<endl;
52+
int mat[M][N] =
53+
{
54+
{1, 2, 3, 1, 8},
55+
{3, 7, 8, 5, 1},
56+
{8, 7, 7, 3, 1},
57+
{8, 1, 2, 3, 9},
58+
};
59+
cout<<"Common eleemnts of each row"<<endl;
60+
printCommonElements(mat);
61+
return 0;
62+
}

0 commit comments

Comments
 (0)