JavaScriptEasy
Intersection of two arrays
Put one array into a Set, then filter the other array to the values the set contains; this is O(n + m) time, and wrapping the result in another Set removes duplicates if each common value should appear once.
Variations to clarify with the interviewer
- Unique intersection (LeetCode 349): each common value once:
[...new Set(a.filter(x => setB.has(x)))]. - With multiplicity (LeetCode 350):
[1,2,2,1]∩[2,2]=[2,2]: count occurrences in aMapand decrement as you match. - Sorted inputs: two pointers, O(n + m) with O(1) extra space.
- Objects: intersect by a key such as
id. - Many arrays: reduce over them, intersecting pairwise; start with the smallest for speed.
Built-in Set methods (ES2025)
setA.intersection(setB), union, difference, symmetricDifference, isSubsetOf and more are now part of the language in up-to-date engines. Feature-detect before relying on them for older browsers.
Complexity
filter+includes: O(n·m), fine only for tiny arrays.- Set lookup: O(n + m) time, O(m) space.
- Sorting first then two pointers: O(n log n + m log m), useful if the data is already sorted.
Code example
js
1// Unique intersection2const intersection = (a, b) => {3 const setB = new Set(b);4 return [...new Set(a.filter((x) => setB.has(x)))];5};6console.log(intersection([1, 2, 2, 3, 4], [2, 2, 4, 6])); // [2, 4]78// With multiplicity9function intersectionWithCounts(a, b) {10 const counts = new Map();11 for (const x of a) counts.set(x, (counts.get(x) ?? 0) + 1);12 const out = [];13 for (const x of b) {14 if (counts.get(x) > 0) {15 out.push(x);16 counts.set(x, counts.get(x) - 1);17 }18 }19 return out;20}21console.log(intersectionWithCounts([1, 2, 2, 1], [2, 2, 3])); // [2, 2]2223// Sorted input: two pointers, O(1) extra space24function intersectSorted(a, b) {25 const out = [];26 let i = 0, j = 0;27 while (i < a.length && j < b.length) {28 if (a[i] === b[j]) { if (out.at(-1) !== a[i]) out.push(a[i]); i++; j++; }29 else if (a[i] < b[j]) i++;30 else j++;31 }32 return out;33}34console.log(intersectSorted([1, 3, 5, 7, 9], [3, 4, 5, 9, 10])); // [3, 5, 9]3536// Objects by key, and many arrays at once37const teamA = [{ id: 1, n: "Ada" }, { id: 2, n: "Linus" }];38const teamB = [{ id: 2, n: "Linus" }, { id: 3, n: "Grace" }];39const idsB = new Set(teamB.map((u) => u.id));40console.log(teamA.filter((u) => idsB.has(u.id)).map((u) => u.n)); // ["Linus"]41console.log([[1, 2, 3, 4], [2, 3, 4], [3, 4, 5]].reduce(intersection)); // [3, 4]4243// Built-in Set methods where available (ES2025)44if (typeof Set.prototype.intersection === "function") console.log([...new Set([1, 2, 3]).intersection(new Set([2, 3, 4]))]); // [2, 3]
Practice this question
Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the JavaScript set.