Lesson 8 of 8
Intersection and difference
- 12 min
- 6 checks
- 3 hints
- Go to task
Goal
From n×m down to n+m
Explanation
“Who signed up for both courses?” and “Who signed up only for the first one?” come up again and again in different forms: shared tags, deleted IDs, missing permissions.
The first solution that comes to mind is a.filter(x => b.includes(x)), which scans all of b for every item in a, so with a thousand items in each you need a million comparisons. It's better to build a Set from b once and then call has for each item, which takes two thousand steps instead of a million.
A common mistake is building the set inside the function you pass to filter. The code a.filter(x => new Set(b).has(x)) builds a new set for every item, which makes it even slower than includes.
Your task
Write intersect(a, b) to return the items found in both arrays, and difference(a, b) to return what's in a but not in b. Both functions must keep the order of a and read b only once.
Checks
6 checks- intersect returns the shared items
- intersect keeps the order of the first array
- difference returns what's only in the first array
- Empty arrays don't cause errors in either function
- intersect reads the second array only once
- difference reads the second array only once