Skip to content

Commit b538892

Browse files
committed
Refactor findCommonItems to O(n + m) using a Set
1 parent 620c969 commit b538892

1 file changed

Lines changed: 29 additions & 8 deletions

File tree

Lines changed: 29 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,35 @@
11
/**
22
* Finds common items between two arrays.
3-
*
4-
* Time Complexity:
5-
* Space Complexity:
6-
* Optimal Time Complexity:
7-
*
3+
4+
* Inefficiency: the original used secondArray.includes() inside firstArray.filter(), which is a loop inside a loop.
5+
6+
* Originally:
7+
* Time Complexity: O(n × m) - filter runs n times and each includes call can scan up to m items (O(n²) if the arrays are the same size).
8+
9+
* Space Complexity: O(n) - the filtered array and the Set hold up to n items.
10+
11+
* Optimal Time Complexity: O(n + m) - every item in both arrays must be read at least once
12+
13+
* After refactor (the complexity was reduced from quadratic to linear time by
14+
using a Set for O(1) average lookups instead of includes):
15+
16+
* Time Complexity: O(n + m) - building secondSet is O(m); the loop over firstArray is O(n) with O(1) average has() checks.
17+
18+
* Space Complexity: O(n + m) - secondSet holds up to m items; commonElements and the final Set hold up to n items.
19+
* Optimal Time Complexity: O(n + m) - every item in both arrays must be read at least once, so we can't do better than linear
20+
*
821
* @param {Array} firstArray - First array to compare
922
* @param {Array} secondArray - Second array to compare
1023
* @returns {Array} Array containing unique common items
1124
*/
12-
export const findCommonItems = (firstArray, secondArray) => [
13-
...new Set(firstArray.filter((item) => secondArray.includes(item))),
14-
];
25+
export const findCommonItems = (firstArray, secondArray) => {
26+
const secondSet = new Set(secondArray);
27+
let commonElements = [];
28+
29+
for(let ele of firstArray){
30+
if(secondSet.has(ele)){
31+
commonElements.push(ele);
32+
}
33+
}
34+
return [...new Set(commonElements)];
35+
};

0 commit comments

Comments
 (0)