Algorithm Steps
- Given two arrays
arr1
andarr2
. - Create a set to store unique elements.
- Insert all elements of
arr1
into the set. - Insert all elements of
arr2
into the set. - The set now contains the union of both arrays with no duplicates.
- Convert the set to a list (or array) if needed and return it.
Union of Two Arrays using Set - Optimal Approach Code
Python
JavaScript
Java
C++
C
def union_of_arrays(arr1, arr2):
result = set()
for num in arr1:
result.add(num)
for num in arr2:
result.add(num)
return list(result)
# Sample Input
arr1 = [1, 2, 4, 5, 6]
arr2 = [2, 3, 5, 7]
print("Union:", union_of_arrays(arr1, arr2))