-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
Union_and_Intersection_of_arrays.cpp
162 lines (142 loc) · 2.57 KB
/
Union_and_Intersection_of_arrays.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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
/* Union of arrays- Print all the elements that are present in both the arrays
Intersection of arrays- Print all the elements that are common in both the arrays
NOTE: Element in the output should be distinct */
using namespace std;
#include<iostream>
#include<algorithm>
/* The array are unsorted */
void Intersection(int arr1[], int arr2[], int n1, int n2)
{
int i = 0, j = 0;
while (i < n1 && j < n2)
{
if (i > 0 && arr1[i] == arr1[i - 1])
{
i += 1;
continue;
}
else if (j > 0 && arr2[j] == arr2[j - 1])
{
j += 1;
continue;
}
// Increase both the iterating variable when common element is found
else if (arr1[i] == arr2[j])
{
cout << arr1[i] << " ";
i += 1;
j += 1;
}
else if (arr2[j] < arr1[i])
{
j += 1;
}
else
{
i += 1;
}
}
}
void Union( int arr1[], int arr2[], int n1, int n2 )
{
int i = 0, j = 0;
//
while (i < n1 && j < n2)
{
if (i > 0 && arr1[i] == arr1[i - 1])
{
i += 1;
continue;
}
else if (j > 0 && arr2[j] == arr2[j - 1])
{
j += 1;
continue;
}
else if (arr1[i] < arr2[j])
{
cout << arr1[i] << " ";
i += 1;
}
else if (arr2[j] < arr1[i])
{
cout << arr2[j] << " ";
j += 1;
}
else
{
cout << arr1[i] << " ";
i += 1;
j += 1;
}
}
// To print remaining elements from arr1
while (i < n1)
{
if (i > 0 && arr1[i] == arr1[i - 1])
{
i += 1;
continue;
}
else
{
cout << arr1[i] << " ";
i += 1;
}
}
// To print remaining elements from arr2
while (j < n2)
{
if (j > 0 && arr2[j] == arr2[j - 1])
{
j += 1;
continue;
}
else
{
cout << arr2[j] << " ";
j += 1;
}
}
}
int main ()
{
int n1,n2;
cin >> n1 >> n2;
int arr1[n1];
int arr2[n2];
for (int i = 0; i < n1; i++)
cin >> arr1[i];
for (int i = 0; i < n2; i++)
cin >> arr2[i];
sort (arr1, arr1 + n1);
sort (arr2, arr2 + n2);
cout<<"UNION"<<endl;
Union(arr1, arr2, n1, n2);
cout<<endl;
cout<<"INTERSECTION"<<endl;
Intersection(arr1, arr2, n1, n2);
return 0;
}
/*
INPUT:
5 3
1 2 3 3 3
1 2 3
OUTPUT:
UNION
1 2 3
INTERSECTION
1 2 3
INPUT:
5 3
1 2 1 1 1
1 1 1
OUTPUT:
UNION
1 2
INTERSECTION
1
Time Complexity: O(n1+n2)
Space Complexity: O(1)
*/