Intersection of Collections
DSA · Hash Maps & Setssyntax
Convert one collection to a set, iterate the other and check membership.
For sorted arrays: use two pointers instead.example
// JavaScript
function intersection(arr1, arr2) {
const set1 = new Set(arr1);
const result = [];
const seen = new Set();
for (const val of arr2) {
if (set1.has(val) && !seen.has(val)) {
result.push(val);
seen.add(val);
}
}
return result;
}
# Python
def intersection(arr1, arr2):
return list(set(arr1) & set(arr2))
# With duplicates preserved:
def intersect_with_dupes(arr1, arr2):
from collections import Counter
c1, c2 = Counter(arr1), Counter(arr2)
return list((c1 & c2).elements())output
intersection([1,2,2,1], [2,2]) → [2]
intersect_with_dupes([1,2,2,1], [2,2]) → [2, 2]Note Set approach: O(n + m) time, O(min(n,m)) space. Sorted two-pointer approach: O(n log n + m log m) time, O(1) extra space. Ask the interviewer: unique results or preserve duplicates? Are inputs sorted?