The concept of intersection is from set theory, so this problem is really simple if we just use Set
s! In mathematics, the intersection of two sets A and B is the set that contains all elements of A that also belong to B.
Set
s are an object type in most languages that allow you to store unique values of most primitives. The strength of set
is that implementation of unordered set
in most programming languages only takes O(1)
worst time complexity for checking the existence of an element. So, we can replace the secondArray.includes(el)
part of previous js code with a set operation!
If we transform our input arrays into sets, we can make use of the filter
method, and apply it to one of the sets-- filtering out anything not in the other set.
xxxxxxxxxx
const first = [4, 9, 5];
const second = [9, 4, 9, 8, 4];
​
function intersection(nums1, nums2) {
const set = new Set(nums1);
const filteredSet = new Set(nums2.filter((n) => set.has(n)));
return [ filteredSet ];
}
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment