876806. Union of Two Arrays with Distinct Elements
Easy
Union of Two Arrays with Distinct Elements
Summary
Given two arrays arr1 and arr2, write a program to find their union. The union of two sets is the set of all elements that are in either set, without duplicates.
Detailed Explanation
To solve this problem, we can iterate through both arrays and add each element to a new array, ensuring that duplicate elements are not included.
Here's the step-by-step breakdown:
- Create an empty array
resultto store the union. - Iterate through
arr1. For each elementx, check if it already exists inresult. If not, addxtoresult. - Repeat step 2 for
arr2. - Return the resulting array.
Here's an ASCII art diagram of the process:
arr1: [1, 2, 3]
arr2: [2, 4, 5]
result = []
foreach x in arr1
if !result.contains(x) then add x to result
result = [1, 2, 3]
foreach y in arr2
if !result.contains(y) then add y to result
result = [1, 2, 3, 4, 5]
The time complexity of this solution is O(n), where n is the total number of elements in both arrays. The space complexity is also O(n), as we need to store all distinct elements in the result array.
Optimized Solutions
Java
public int[] union(int[] arr1, int[] arr2) {
Set<Integer> set = new HashSet<>();
for (int x : arr1) {
if (!set.contains(x)) {
set.add(x);
}
}
for (int y : arr2) {
if (!set.contains(y)) {
set.add(y);
}
}
int[] result = new int[set.size()];
int i = 0;
for (int x : set) {
result[i++] = x;
}
return result;
}