Skip to content

Commit 0aae0c9

Browse files
committed
Refactor findCommonItems function to improve time and space complexity, and update documentation
1 parent 7b28f6d commit 0aae0c9

1 file changed

Lines changed: 4 additions & 27 deletions

File tree

Lines changed: 4 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -1,40 +1,17 @@
11
/**
22
* Finds common items between two arrays.
33
*
4-
* Time Complexity: O(n * m)
5-
* Space Complexity: O(n)
6-
* Optimal Time Complexity: O(n + m)
4+
* Time Complexity: O(n + m)
5+
* Space Complexity: O(n + m)
76
*
87
* @param {Array} firstArray - First array to compare
98
* @param {Array} secondArray - Second array to compare
109
* @returns {Array} Array containing unique common items
1110
*/
1211

13-
export const findCommonItems = (firstArray, secondArray) => [
14-
...new Set(firstArray.filter((item) => secondArray.includes(item))),
15-
];
16-
17-
// Time complexity is O(n * m) because for each item in the first array,
18-
// includes() may search through the entire second array.
19-
20-
// Space complexity is O(n) because filter() creates a new array
21-
// and Set stores unique common items.
22-
23-
// Optimal time complexity is O(n + m) because using Sets
24-
// allows us to check for common items more efficiently.
2512
export function findCommonItems(firstArray, secondArray) {
13+
const firstSet = new Set(firstArray);
2614
const secondSet = new Set(secondArray);
27-
const commonItems = new Set();
2815

29-
for (const item of firstArray) {
30-
if (secondSet.has(item)) {
31-
commonItems.add(item);
32-
}
33-
}
34-
35-
return [...commonItems];
16+
return [...firstSet.intersection(secondSet)];
3617
}
37-
38-
// Time complexity: O(n + m)
39-
// Space complexity: O(n + m)
40-
// Optimal time complexity: O(n + m)

0 commit comments

Comments
 (0)