-
-
Notifications
You must be signed in to change notification settings - Fork 29
Expand file tree
/
Copy pathfindCommonItems.js
More file actions
27 lines (24 loc) · 864 Bytes
/
findCommonItems.js
File metadata and controls
27 lines (24 loc) · 864 Bytes
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
/**
* Finds common items between two arrays.
*
* Time Complexity:
* Space Complexity:
* Optimal Time Complexity:
*
* @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 firstArr = new Set(firstArray);
const secondArr = new Set(secondArray);
// return [...firstArr].filter((arr) => secondArr.has(arr));
return [...firstArr.intersection(secondArr)];
};
// * https://www.w3schools.com/js/js_set_methods.asp#mark_set_new
// * Time Complexity: O(m+n)
// * Space Complexity: O(m+n)
// * Optimal Time Complexity: O(m+n)