Array Intersection (Easy)
Good morning! Here's our prompt for today.
You may see this problem at Salesforce, Godaddy, Palantir, Dropbox, Intuit, Airbnb, Pivotal, Snowflake, Flatiron Health, Gitlab, Asana, C3 Ai, Sony, and Expedia.
As we ease our way into the course, we'll want to start with the basic data structures and their operations. However, don't be fooled how fundamental these things are!
Interviewers will often test you on things that are deceptively easy. We saw this in Reverse a String, and will see more in future challenges. But sometimes you might get tested on a concept that, while a bit trivial, is really useful in day to day software engineering.
One of those things is array manipulation, or basically doing things to an array that creates some kind of transformation.
Prompt
Can you write a function that takes two arrays as inputs and returns to us their intersection? We can call the method intersection. Let's return the intersection of the two inputs in the form of an array. As a reminder, the definition of an intersection of two sets A and B is the set containing all elements of A that also belong to B (or equivalently, all elements of B that also belong to A).

Note that all elements in the final result should be unique. Here's one example:
1const nums1 = [1, 2, 2, 1];
2const nums2 = [2, 2];
3
4intersection(nums1, nums2);
5// [2]And here's another one:
1const nums1 = [4,9,5];
2const nums2 = [9,4,9,8,4];
3
4intersection(nums1, nums2);
5// [9, 4]Constraints
- Length of the array <=
100000 - The values in the array will be in the range
-1000000000and1000000000 - Expected time complexity:
O(n+m)wherenandmare the lengths of the array. - Expected space complexity:
O(max(n,m)).
xxxxxxxxxxvar assert = require('assert');function intersection(nums1, nums2) { // fill this in return [];}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);}