You are given two integer arrays arr1
and arr2
. Your task is to find all the elements that are common between the two arrays. Both the arrays can contain duplicates, but you should return each common element only once. The result can be returned in any order.
Example:
arr1 = [1, 2, 2, 1]
arr2 = [2, 2]
Output: [2]
arr1 = [4, 9, 5]
arr2 = [9, 4, 9, 8, 4]
Output: [9, 4]
To solve the problem, we can use a two-step approach:
arr1
to a set called set1
.arr2
to a set called set2
.set1
and set2
.def find_common_elements(arr1, arr2):
# Convert arrays to sets
set1 = set(arr1)
set2 = set(arr2)
# Find the intersection of both sets
common_elements = set1.intersection(set2)
# Convert the result back to a list
return list(common_elements)
# Example usage
arr1 = [1, 2, 2, 1]
arr2 = [2, 2]
print(find_common_elements(arr1, arr2)) # Output: [2]
arr1 = [4, 9, 5]
arr2 = [9, 4, 9, 8, 4]
print(find_common_elements(arr1, arr2)) # Output: [9, 4]
This code correctly finds the common elements between two arrays, ensures no duplicates in the result, and handles empty inputs gracefully.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?