![]() |
VOOZH | about |
Given two sorted arrays a[] and b[] with distinct elements, the task is to return union of both the arrays in sorted order.
Note: Union of two arrays is an array having all distinct elements that are present in either array.
Examples:
Input: a[] = {1, 2, 3}, b[] = {2, 5, 7}
Output: {1, 2, 3, 5, 7}
Explanation: 1, 2, 3, 5 and 7 are the distinct elements present in either array.Input: a[] = {2, 4, 5}, b[] = {1, 2, 3, 4, 5}
Output: {1, 2, 3, 4, 5}
Explanation: 1, 2, 3, 4 and 5 are the distinct elements present in either array.
Table of Content
The idea is to add all elements from the first array a[] to result array. Then, iterate through the second array b[] and add its elements to the result only if they were not present in a[]. Finally, sort the result array to get the union in sorted order.
1 2 3 5 7
Time Complexity: O(n*m), 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.
To know more about the implementation, please refer to Union of Two Sorted Arrays.
The idea is to first add all elements from the first array into the result. Now, iterate over the second array and for each element, add the element to the result only if it was not present in the first array. Since the first array is sorted, we can use Binary Search to search for an element in log(n) time. After pushing all the elements to the result, sort the result.
1 2 3 5 7
Time Complexity: O((n+m)*log(m+n)), as we are sorting the result array.
Auxiliary Space: O(1)
The idea is to finds 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.
Once one array is fully traversed, any remaining elements from the other array are added.
1 2 3 5 7
Time Complexity: O(n+m), where n is the size of array a[] and m is the size of array b[].
Auxiliary Space: O(1)
Related Articles: