Good morning! Here's our prompt for today.
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
-1000000000
and1000000000
- Expected time complexity:
O(n+m)
wheren
andm
are the lengths of the array. - Expected space complexity:
O(max(n,m))
.
Try to solve this here or in Interactive Mode.
How do I practice this challenge?
xxxxxxxxxx
'PASSED: `intersection([4,17,4,4,15,16,17,6,7],[15,2,6,20,17,17,8,4,5])` should return `[15,6,17,4]`'
var 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);
}
​
try {
assertSameMembers(
Tired of reading? Watch this video explanation!
To change the speed of the video or see it in full screen, click the icons to the right of the progress bar.
We'll now take you through what you need to know.
How do I use this guide?