-
-
Notifications
You must be signed in to change notification settings - Fork 29
Expand file tree
/
Copy pathfindCommonItems.js
More file actions
26 lines (23 loc) · 809 Bytes
/
findCommonItems.js
File metadata and controls
26 lines (23 loc) · 809 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
/**
* 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) => {
let firstArr = new Set(firstArray);
let secondArr = new Set(secondArray);
return [...firstArr].filter((arr) => secondArr.has(arr));
};
// * 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)