Skip to content

Commit 5a44bf2

Browse files
authored
Merge pull request #565 from shraddhamishra611/master
Count Union of two arrays
2 parents f2f98e0 + 9fa7cad commit 5a44bf2

File tree

1 file changed

+50
-0
lines changed

1 file changed

+50
-0
lines changed

DSA 450 GFG/Union_Arrays.cpp

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
/*
2+
Union of the two arrays can be defined as the set containing distinct elements from both the arrays.
3+
If there are repetitions, then only one occurrence of element should be considered in the union.
4+
The final count should be printed.
5+
*/
6+
#include <bits/stdc++.h>
7+
using namespace std;
8+
9+
class Solution{
10+
public:
11+
//Function to return the count of number of elements in union of two arrays.
12+
int doUnion(int a[], int n, int b[], int m) {
13+
set<int>s;
14+
for (int i = 0; i < n; i++)
15+
s.insert(a[i]);
16+
17+
for (int i = 0; i < m; i++)
18+
s.insert(b[i]); //duplicates will not be added, property of sets
19+
20+
return s.size();
21+
}
22+
};
23+
24+
25+
int main() {
26+
//enter number of test cases.
27+
int t;
28+
cin >> t;
29+
30+
while(t--){
31+
32+
int n, m;
33+
//accept size of both the arrays
34+
cin >> n >> m;
35+
int a[n], b[m];
36+
37+
//accept the arrays
38+
for(int i = 0;i<n;i++)
39+
cin >> a[i];
40+
41+
for(int i = 0;i<m;i++)
42+
cin >> b[i];
43+
44+
Solution ob;
45+
cout << ob.doUnion(a, n, b, m) << endl; //count is displayed
46+
47+
}
48+
49+
return 0;
50+
}

0 commit comments

Comments
 (0)