Skip to content

Commit ced4ca0

Browse files
committed
findcommonitems func complexity analysis + refactoring for better efficiency
1 parent 070514b commit ced4ca0

File tree

1 file changed

+27
-3
lines changed

1 file changed

+27
-3
lines changed

Sprint-1/JavaScript/findCommonItems/findCommonItems.js

Lines changed: 27 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,30 @@
99
* @param {Array} secondArray - Second array to compare
1010
* @returns {Array} Array containing unique common items
1111
*/
12-
export const findCommonItems = (firstArray, secondArray) => [
13-
...new Set(firstArray.filter((item) => secondArray.includes(item))),
14-
];
12+
// export const findCommonItems = (firstArray, secondArray) => [
13+
// ...new Set(firstArray.filter((item) => secondArray.includes(item))),
14+
// ];
15+
// My analysis report
16+
// The function have a hidden nested loop using filter() and includes() This makes it quite expensive for us
17+
18+
// Time Complexity
19+
// .filter() does n operation and .includes() does m operation since it is a nested loop the time complexity would be the product of the two complexities
20+
// O (n * m )
21+
// Space Complexity
22+
// .filter creates a temporary array to store common items O(n) space and "Set" also takes O(m) space. This is un avoidable if we use this nested loop
23+
24+
// The inefficiency is on the hidden nested loop
25+
26+
export const findCommonItems = (firstArray, secondArray) => {
27+
const arraySet = new Set(secondArray);
28+
const commonItems = firstArray.filter((item) => {
29+
return arraySet.has(item);
30+
});
31+
32+
return [...new Set(commonItems)];
33+
};
34+
35+
36+
// Time complexity is O(n + m) which is O(n) complexity from line 28 and o(m) complexity from line 32. i neglected line 27 complexity since it is O(1)
37+
// Space Complexity stays almost same
38+
// and we can say refactoring this code makes it fast.

0 commit comments

Comments
 (0)