-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0349-intersection-of-two-arrays.js
More file actions
33 lines (28 loc) · 1.04 KB
/
0349-intersection-of-two-arrays.js
File metadata and controls
33 lines (28 loc) · 1.04 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
/**
* Intersection Of Two Arrays
* Time Complexity: O(N + M)
* Space Complexity: O(N + M)
*/
var intersection = function (numsArrayOne, numsArrayTwo) {
const uniqueElementsFromFirst = new Set(numsArrayOne);
const uniqueElementsFromSecond = numsArrayTwo.reduce((accumulatedSetForSecond, currentNumberFromSecond) => {
accumulatedSetForSecond.add(currentNumberFromSecond);
return accumulatedSetForSecond;
}, new Set());
const intersectionResultContainer = [];
let iteratingSet;
let checkingSet;
if (uniqueElementsFromFirst.size < uniqueElementsFromSecond.size) {
iteratingSet = uniqueElementsFromFirst;
checkingSet = uniqueElementsFromSecond;
} else {
iteratingSet = uniqueElementsFromSecond;
checkingSet = uniqueElementsFromFirst;
}
for (const valueFromIteratingSet of iteratingSet) {
if (checkingSet.has(valueFromIteratingSet)) {
intersectionResultContainer.push(valueFromIteratingSet);
}
}
return intersectionResultContainer;
};