![]() |
VOOZH | about |
Given two sorted arrays a[] and b[], the task is to return union of both the arrays in sorted order. Union of two arrays is an array having all distinct elements that are present in either array. The input arrays may contain duplicates.
Examples:
Input: a[] = {1, 1, 2, 2, 2, 4}, b[] = {2, 2, 4, 4}
Output: {1, 2, 4}
Explanation: 1, 2 and 4 are the distinct elements present in either array.Input: a[] = {3, 5, 10, 10, 10, 15, 15, 20}, b[] = {5, 10, 10, 15, 30}
Output: {3, 5, 10, 15, 20, 30}
Explanation: 3, 5, 10, 15, 20 and 30 are the distinct elements present in either array.
Table of Content
The intuition behind this approach is to gather unique elements from two arrays by checking each element against the current result array. The idea is to traverse both the arrays and for each element, check if the element is present in the result or not. If not, then add this element to the result.
1 2 4
Time Complexity: O((n + m)2), where n is size of a[] and m is size of b[]
Auxiliary Space: O(1)
The approach is to insert all elements from both arrays, a[] and b[], into a set. Since a set automatically removes duplicates, it gives us the union of the two arrays. Also, the set keeps the elements in sorted order, so after inserting them, we can store these sorted and unique elements in a result array.
Note: In Python and JavaScript, the set data structure does not store the elements in sorted order, so we need to explicitly sort the union array.
1 2 4
Time Complexity: O((n + m) * (log (n + m))) , where n is the size of array a[] and m is the size of array b[]
Auxiliary Space: O(n + m)
The idea is to find the union of two sorted arrays using merge step in merge sort. We maintain two pointers to traverse both arrays simultaneously.
- If the element in first array is smaller, add it to the result and move the pointer of first array forward.
- If the element in second array is smaller, add it to the result and move the pointer of second array forward.
- If both elements are equal, add one of them and move both the pointers forward.
Also, while traversing both the arrays, we will compare the current element with its previous element and skip the current element if it is same as previous element. This will ensure that the union will contain only distinct elements.
1 2 4
Time Complexity: O(n + m), Where n is the size of a[] and m is the size of b[]
Auxiliary Space: O(1)
Related Articles: