![]() |
VOOZH | about |
Given two arrays a[] and b[], 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, 2, 1], b[] = [3, 2, 2, 3, 3, 2]
Output : [3, 2, 1]
Explanation: 3, 2 and 1 are the distinct elements present in either array.Input : a[] = [1, 2, 3], b[] = [4, 5, 6]
Output : [1, 2, 3, 4, 5, 6]
Explanation: 1, 2, 3, 4, 5 and 6 are the elements present in either array.
Table of Content
The idea is to traverse both the arrays a[] and b[] 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 3
Time Complexity: O((n + m)2), 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.
3 2 1
Related Articles: