One Pager Cheat Sheet
- We need to write a function called
intersectionwhich 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
resultarray. - We can make use of
Sets and thefiltermethod to find the intersection of two arrays inO(1)time complexity. - The creation of a
setfrom an array ofnelements and checking for its existence in a second array ofmelements 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.
xxxxxxxxxx65
}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
Alright, well done! Try another walk-through.
If you had any problems with this tutorial, check out the main forum thread here.


