-
-
Notifications
You must be signed in to change notification settings - Fork 29
Expand file tree
/
Copy pathfindCommonItems.js
More file actions
32 lines (26 loc) · 1.08 KB
/
findCommonItems.js
File metadata and controls
32 lines (26 loc) · 1.08 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
/**
* Finds common items between two arrays.
*
* Time Complexity: O(n * m) - filter checks each element of firstArray and includes scans secondArray
* Space Complexity: O(n) - filter creates a new array where size grows as the input of matches grows. Same thing with set.
* Optimal Time Complexity: O(n + m) - each element must be examined at least once; using a Set allows O(1) lookups
*
* @param {Array} firstArray - First array to compare
* @param {Array} secondArray - Second array to compare
* @returns {Array} Array containing unique common items
*/
// export const findCommonItems = (firstArray, secondArray) => [
// ...new Set(firstArray.filter((item) => secondArray.includes(item))),
// ];
export const findCommonItems = (firstArray, secondArray) => {
const arrayToSet = new Set(secondArray);
const uniqueCommonItems = [];
const checkedItems = new Set();
for (const element of firstArray) {
if (arrayToSet.has(element) && !checkedItems.has(element)) {
checkedItems.add(element);
uniqueCommonItems.push(element);
}
}
return uniqueCommonItems;
};