-
-
Notifications
You must be signed in to change notification settings - Fork 29
Expand file tree
/
Copy pathfindCommonItems.js
More file actions
25 lines (22 loc) · 808 Bytes
/
findCommonItems.js
File metadata and controls
25 lines (22 loc) · 808 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:
* ANSWER: O(n + m)
Because both arrays are processed once and we iterate through them to find common elements.
* Space Complexity:
ANSWER: O(n + m)
because two sets are created
* Optimal Time Complexity:
ANSWER: O(n + m)
Because we must check all elements in both arrays (or sets) at least once.
*
* @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) => {
const firstSet = new Set(firstArray);
const secondSet = new Set(secondArray);
return [...firstSet.intersection(secondSet)];
};