Skip to main content

Union Of Two Arrays

Problem​

Given two arrays a[] and b[] of size n and m respectively. The task is to find the number of elements in the union between these two arrays.

Union of the two arrays can be defined as the set containing distinct elements from both the arrays. If there are repetitions, then only one occurrence of element should be printed in the union.

Note: Elements are not necessarily distinct.

Examples:​

Example 1:

Input:
5 3
1 2 3 4 5
1 2 3
Output:
5
Explanation:
1, 2, 3, 4 and 5 are the
elements which comes in the union set
of both arrays. So count is 5.

Example 2:

Input:
6 2
85 25 1 32 54 6
85 2
Output:
7
Explanation:
85, 25, 1, 32, 54, 6, and
2 are the elements which comes in the
union set of both arrays. So count is 7.

Your Task:​

Complete doUnion function that takes a, n, b, m as parameters and returns the count of union elements of the two arrays. The printing is done by the driver code.

  • Expected Time Complexity: O(n+m)O(n+m)
  • Expected Auxilliary Space: O(n+m)O(n+m)

Constraints:​

  • 1≤n,m≤1051 ≤ n, m ≤ 10^5
  • 0≤a[i],b[i]<1050 ≤ a[i], b[i] < 10^5

Solution​

Python​

def doUnion(self,a,n,b,m):
set1 = set(a)
set2 = set(b)
result = list(set1.union(set2))
return len(result)

Java​

public static int doUnion(int a[], int n, int b[], int m) {
TreeSet<Integer> set = new TreeSet<>();
for (int i : a)
set.add(i);
for (int i : b)
set.add(i);
ArrayList<Integer> list = new ArrayList<>();
for (int i : set)
list.add(i);
return list.size();
}

C++​

int doUnion(int a[], int n, int b[], int m)  {
set<int> s;
for (int i = 0; i < n; i++) {
s.insert(a[i]);
}
for (int i = 0; i < m; i++) {
s.insert(b[i]);
}
vector<int> vec(s.begin(), s.end());
return vec.size();
}

C​

int doUnion(int a[], int n, int b[], int m) {
int *unionSet = (int *)malloc((n + m) * sizeof(int));
int i, j;
int unionSize = 0;
for (i = 0; i < n; i++) {
unionSet[unionSize++] = a[i];
}
for (i = 0; i < m; i++) {
int found = 0;
for (j = 0; j < unionSize; j++) {
if (b[i] == unionSet[j]) {
found = 1;
break;
}
}
if (!found) {
unionSet[unionSize++] = b[i];
}
}
free(unionSet);
return unionSize;
}
  • Time Complexity: O(m∗log(m)+n∗log(n))O(m*log(m) + n*log(n))
  • Auxiliary Space: O(m+n)O(m + n)