To find the union of two arrays means to combine all values that are present in either of the arrays, but without repeating any value. This is especially important when the arrays have duplicate values — we want each element to appear only once in the result.
The most efficient way to do this is by using a Set
data structure. Sets automatically discard duplicate values, so you can insert all elements from both arrays into the set, and it will ensure that only unique values are kept.
What if both arrays are normal (non-empty)?
If both arr1
and arr2
contain values — whether overlapping or not — adding all elements to a set will result in a list of all distinct elements. For example, if arr1 = [1, 2, 3]
and arr2 = [3, 4, 5]
, the union will be [1, 2, 3, 4, 5]
. The duplicate 3
is included only once.
What if one array is empty?
If either arr1
or arr2
is empty, then the union is simply the unique values from the non-empty array. For example, if arr1 = []
and arr2 = [7, 8]
, the union will be [7, 8]
.
What if both arrays are empty?
If both arrays are empty, then there are no values to include in the union. So the result will also be an empty array: []
.
What if arrays have only repeated values?
If both arrays contain only repeated values — even if they are the same — the union result will include just that one value. For instance, arr1 = [1, 1, 1]
and arr2 = [1, 1]
→ union is [1]
.
Why is this method optimal?
Using a Set
helps us achieve optimal performance because inserting into a set has an average time complexity of O(1)
per element. So the overall time complexity becomes O(n + m)
, where n
and m
are the lengths of the two arrays.
This makes the solution both simple to implement and highly efficient, even for large input sizes.