-
Notifications
You must be signed in to change notification settings - Fork 1k
/
Copy pathFind_Common_Element_in_matrix.cpp
95 lines (73 loc) · 1.83 KB
/
Find_Common_Element_in_matrix.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
/* Find a Common element in rows of a given row-wise sorted matrix. */
#include<bits/stdc++.h>
using namespace std;
/* Function to find common element in the matrix */
int solve()
{
/* Input row = size of row.
Input col = size of column. */
int row,col;
cin >> row >> col;
/* Input elements in matrix. */
int a[row][col];
for (int i = 0; i < row; ++i)
{
for (int j = 0; j < col; ++j)
{
cin >> a[i][j];
}
}
/* Create a hash map to store
count of element */
unordered_map<int, int> count;
for (int i = 0; i < row; i++) {
for (int j = 1; j < col; j++) {
/* Insert elements of the first row and
initialize them with a value of 1 */
if (i == 0) {
count[a[0][i]] = 1;
}
/* Check if the current element exists
in the map and first in the current row */
if (a[i][j] != a[i][j - 1])
count[a[i][j]]++;
}
}
/* Return the element having a count 1 */
for (auto element : count) {
if (element.second == row)
return element.first;
}
/* Return the element having a count not equal to 1 */
return -1;
}
int main()
{
int common = solve();
if (common == -1)
cout << "No Common element"<< endl;
else
cout << "Common element is : " << common << endl;
return 0;
}
/*
Test cases :
Input 1 :
4 5
1 2 3 4 5
2 4 5 8 10
3 5 7 9 11
1 3 5 7 9
Output 1 :
Common element is : 5
Input 2 :
4 5
2 4 3 8 7
1 3 5 6 8
1 2 3 1 3
4 5 0 2 3
Output 2 :
No Common element
Time complexity: O(r*c)
Space Complexity: O(1)
*/