Union of Two Arrays - Optimal Approach

Union of Two Arrays - Optimal Approach

Visualization

Algorithm Steps

  1. Given two arrays arr1 and arr2.
  2. Create a set to store unique elements.
  3. Insert all elements of arr1 into the set.
  4. Insert all elements of arr2 into the set.
  5. The set now contains the union of both arrays with no duplicates.
  6. 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))