Return the common elements of two arrays (e.g. [1,2,2,3] and [2,3,4] -> [2,3] for the distinct version).
Put one array’s elements in a hash set, then scan the other and collect elements present in the set (moving matches into a result set to avoid repeats). O(n + m). Sorting both and using two pointers is the O(1)-extra-space alternative.
public static Set<Integer> intersection(int[] a, int[] b) {
Set<Integer> set = new HashSet<>();
for (int x : a) set.add(x);
Set<Integer> out = new LinkedHashSet<>();
for (int x : b) if (set.contains(x)) out.add(x);
return out;
}function intersection(a, b) {
const set = new Set(a);
return [...new Set(b.filter(x => set.has(x)))];
}def intersection(a, b):
return list(set(a) & set(b))Set intersection answers "which records exist in both systems?" — a routine reconciliation across two data sources.
Should duplicates in the inputs appear multiple times in the result?