Skip to content

Commit 4aa063a

Browse files
committed
refactor code for find commonItems
1 parent b2a67d4 commit 4aa063a

1 file changed

Lines changed: 17 additions & 6 deletions

File tree

Lines changed: 17 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,25 @@
11
/**
22
* Finds common items between two arrays.
33
*
4-
* Time Complexity:
5-
* Space Complexity:
6-
* Optimal Time Complexity:
4+
* Time Complexity:O(n+m) it build set and loop through arrays once
5+
* Space Complexity: store second array in set
6+
* Optimal Time Complexity:O(m+n)
77
*
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+
// ...new Set(firstArray.filter((item) => secondArray.includes(item))),
14+
// ];
15+
// Refactored to use a Set for faster lookups, making the code more efficient
16+
export const findCommonItems = (firstArray, secondArray) => {
17+
const secondArraySet = new Set(secondArray);
18+
const resultSet = new Set();
19+
for (const element of firstArray) {
20+
if (secondArraySet.has(element)) {
21+
resultSet.add(element);
22+
}
23+
}
24+
return [...resultSet];
25+
};

0 commit comments

Comments
 (0)