Understanding the Problem: Union of Two Arrays
The goal is to compute the union of two arrays. That means we need to gather all the elements from both arrays, but include each element only once, even if it appears multiple times in either array.
For example, if the two arrays are:
arr1 = [1, 2, 3]
arr2 = [3, 4, 5]
The result should be [1, 2, 3, 4, 5]
— note that 3
is not repeated.
Step-by-Step Approach
Step 1: Use a Set to Handle Uniqueness
A Set
in most programming languages (like JavaScript, Python, Java) automatically keeps only unique values. This makes it perfect for solving union problems.
Step 2: Add All Elements from Both Arrays
Loop through each array, and add every element to the set. The set will automatically ignore duplicates.
Step 3: Convert the Set to a List (if needed)
Once all elements are added to the set, you can convert it back to an array or list to return the result.
Detailed Example for Beginners
Let’s consider:
arr1 = [1, 2, 3, 2]
arr2 = [2, 3, 4, 5]
1. Add from arr1:
- Add 1 → set is {1}
- Add 2 → set is {1, 2}
- Add 3 → set is {1, 2, 3}
- Add 2 again → set remains {1, 2, 3}
2. Add from arr2:
- Add 2 → already in set
- Add 3 → already in set
- Add 4 → set is {1, 2, 3, 4}
- Add 5 → set is {1, 2, 3, 4, 5}
Final result: [1, 2, 3, 4, 5]
Handling Edge Cases Intuitively
Case 1: One array is empty
arr1 = []
arr2 = [7, 8]
The result is just the unique values of the second array: [7, 8]
Case 2: Both arrays are empty
arr1 = []
arr2 = []
The result is an empty array: []
Case 3: Arrays contain only repeated values
arr1 = [1, 1, 1]
arr2 = [1, 1]
Set will store only one 1
, so the result is: [1]
Case 4: Arrays with completely distinct values
arr1 = [10, 20]
arr2 = [30, 40]
No overlap — the result is just a merge of all elements: [10, 20, 30, 40]
Why is This Method Efficient?
Using a set allows for average O(1)
time for insertions. So processing both arrays of lengths n
and m
takes O(n + m)
time.
This method is fast, intuitive, and works well even with large arrays.
Comments
Loading comments...