![]() |
VOOZH | about |
Given two arrays a[] and b[] with distinct elements, the task is to return union of both the arrays in any 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[] = {5, 2, 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 a result array. Then iterate through the second array b[] and add its elements to the result only if they were not present in a[]. This ensures that all the elements from both arrays are included, with no duplicates.
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 idea is to use a Hash Set, which helps in keeping only unique elements by removing duplicates. We first create an empty Hash Set and add elements from both arrays. The Hash Set ensures that no duplicates are stored. After adding all the elements, we can create the final union array by iterating through the Hash Set.
To know more about the implementation, please refer to the efficient approach in Union of Two Arrays.
Related Articles: