One Pager Cheat Sheet
- We need to write a function called
intersection
which takes two arrays as inputs and returns their intersection as a unique set of values. - We can brute force the intersection of two arrays by looping through the first array, checking if each element exists in the second array, and then adding the element to an object to ensure uniqueness of the items in the
result
array. - We can make use of
Set
s and thefilter
method to find the intersection of two arrays inO(1)
time complexity. - The creation of a
set
from an array ofn
elements and checking for its existence in a second array ofm
elements takesO(m+n)
time complexity. - The problem helps you learn
when to use the Set data structure
, thereby emphasizing mathematics and interview preparation.
This is our final solution.
To visualize the solution and step through the below code, click Visualize the Solution on the right-side menu or the VISUALIZE button in Interactive Mode.
xxxxxxxxxx
65
}
var assert = require('assert');
​
function intersection(nums1, nums2) {
const set = new Set(nums1);
const fileredSet = new Set(nums2.filter((n) => set.has(n)));
return [fileredSet];
}
​
try {
assert.deepEqual(intersection([6, 0, 12, 10, 16], [3, 15, 18, 20, 15]), []);
​
console.log(
'PASSED: `intersection([6,0,12,10,16],[3,15,18,20,15])` should return `[]`'
);
} catch (err) {
console.log(err);
}
​
try {
assert.deepEqual(intersection([1, 5, 2, 12, 6], [13, 10, 9, 5, 8]), [5]);
​
console.log(
'PASSED: `intersection([1,5,2,12,6],[13,10,9,5,8])` should return `[5]`'
);
} catch (err) {
console.log(err);
}
​
try {
assertSameMembers(
intersection(
[4, 17, 4, 4, 15, 16, 17, 6, 7],
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment
You're doing a wonderful job. Keep going!
If you had any problems with this tutorial, check out the main forum thread here.