Skip to content

Commit 69205b2

Browse files
committed
feat: Optimise findCommonItems function and reduce complexity
1 parent 410e893 commit 69205b2

1 file changed

Lines changed: 13 additions & 6 deletions

File tree

Lines changed: 13 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,21 @@
11
/**
22
* Finds common items between two arrays.
33
*
4-
* Time Complexity:
5-
* Space Complexity:
6-
* Optimal Time Complexity:
4+
* Initial code has this and can be refactored for optimisation
5+
* Time Complexity: O(nm)
6+
* Space Complexity: O(n)
7+
* Optimal Time Complexity: O(n + m)
78
*
89
* @param {Array} firstArray - First array to compare
910
* @param {Array} secondArray - Second array to compare
1011
* @returns {Array} Array containing unique common items
1112
*/
12-
export const findCommonItems = (firstArray, secondArray) => [
13-
...new Set(firstArray.filter((item) => secondArray.includes(item))),
14-
];
13+
// export const findCommonItems = (firstArray, secondArray) => [
14+
// ...new Set(firstArray.filter((item) => secondArray.includes(item))),
15+
// ];
16+
// The initial solution had an expensive operation of .includes(item) search on the secondArray, resulting in O(nm) time complexity. The optimised code stores the secondArray in a set and allows O(1) lookup and reduce the complexity to O(n+m)
17+
export const findCommonItems = (firstArray, secondArray) => {
18+
const secondSet = new Set(secondArray);
19+
20+
return [...new Set(firstArray.filter((item) => secondSet.has(item)))];
21+
};

0 commit comments

Comments
 (0)