Coding Challenge Practice - Question 78
Source: Dev.to
Problem Description
The task is to find the intersection given two arrays.
Solution Approach
Since the arrays are not sorted and may contain duplicates, a fast lookup method with duplicate removal is ideal. Convert one array into a Set, loop through the other array, and collect matching items in a result Set to ensure each intersecting value appears only once.
Implementation
function getIntersection(arr1, arr2) {
// Convert the first array to a Set for O(1) lookups
const set1 = new Set(arr1);
const result = new Set();
// Iterate over the second array and add common items to the result set
for (const item of arr2) {
if (set1.has(item)) {
result.add(item);
}
}
// Return the intersection as an array
return [...result];
}
That’s all folks!