⬅ Previous Topic
Linear Search in ArrayNext Topic ⮕
Find Missing Number in Array⬅ Previous Topic
Linear Search in ArrayNext Topic ⮕
Find Missing Number in ArrayTopic Contents
You are given two arrays arr1
and arr2
. Your task is to return their union — a collection of all distinct elements that appear in either of the arrays.
The union should not contain any duplicate elements. The result can be returned in any order.
If both arrays are empty, return an empty array.
arr1
and arr2
.arr1
into the set.arr2
into the set.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))
Case | Time Complexity | Explanation |
---|---|---|
Best Case | O(n + m) | Each element from both arrays is inserted into a set, which takes constant time per insertion on average. Best and worst case remain the same as all elements need to be processed. |
Average Case | O(n + m) | On average, inserting n elements from the first array and m elements from the second into a set results in linear time complexity. |
Average Case | O(n + m) | Even in the worst case (e.g., hash collisions), we must iterate through all elements of both arrays once, so the time remains linear. |
O(n + m)
Explanation: A set is used to store up to all unique elements from both arrays. In the worst case, none of the elements are duplicates, resulting in a total of n + m unique entries.
⬅ Previous Topic
Linear Search in ArrayNext Topic ⮕
Find Missing Number in ArrayYou can support this website with a contribution of your choice.
When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.