Skip to content

Commit 902546e

Browse files
author
Fatma Degirmenci
committed
Refactor findCommonItems using a Set for faster lookups
1 parent 0313954 commit 902546e

1 file changed

Lines changed: 9 additions & 7 deletions

File tree

Lines changed: 9 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,16 @@
11
/**
22
* Finds common items between two arrays.
33
*
4-
* Time Complexity:
5-
* Space Complexity:
6-
* Optimal Time Complexity:
7-
*
4+
* Time Complexity: We are checking two arrays. If the first array has length n and the second has length m, the time complexity is O(n * m),
5+
because filter iterates over the first array and includes scans the second array for each element.
6+
* Space Complexity: A new Set is created to store unique common items, which in the worst case can be the size of the first array --> O(n).
7+
* Optimal Time Complexity: By converting one array to a Set, we can check membership in O(1) for each element of the other array, reducing the time complexity to O(n + m).
88
* @param {Array} firstArray - First array to compare
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+
const firstArr = new Set(firstArray); //O(n)
14+
const commons = secondArray.filter((el) => firstArr.has(el)); //O(m)
15+
return [...new Set(commons)]; // remove duplicates
16+
};

0 commit comments

Comments
 (0)