-
-
Notifications
You must be signed in to change notification settings - Fork 29
Expand file tree
/
Copy pathfindCommonItems.js
More file actions
26 lines (22 loc) · 701 Bytes
/
findCommonItems.js
File metadata and controls
26 lines (22 loc) · 701 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
/**
* Finds common items between two arrays.
*
* Time Complexity:O(n+m) it build set and loop through arrays once
* Space Complexity: store second array in set
* Optimal Time Complexity:O(m+n)
*
* @param {Array} firstArray - First array to compare
* @param {Array} secondArray - Second array to compare
* @returns {Array} Array containing unique common items
*/
// Refactored to use a Set for faster lookups, making the code more efficient
export const findCommonItems = (firstArray, secondArray) => {
const setB = new Set(secondArray);
const common = new Set();
for (const item of firstArray) {
if (setB.has(item)) {
common.add(item);
}
}
return [...common];
};