Skip to content

Commit b9d4780

Browse files
committed
find common items
1 parent 6c97572 commit b9d4780

1 file changed

Lines changed: 19 additions & 7 deletions

File tree

Lines changed: 19 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,26 @@
11
/**
22
* Finds common items between two arrays.
33
*
4-
* Time Complexity:
5-
* Space Complexity:
6-
* Optimal Time Complexity:
7-
*
4+
* Time Complexity: O(n * m)
5+
* Space Complexity: O(k)---> where k is the number of common items
6+
* Optimal Time Complexity: O(n + m)
7+
* Explanation: The function uses the filter method to iterate through each item in the first array and
8+
* checks if it exists in the second array using the includes method.
9+
* This results in a time complexity of O(n * m) because for each item in the first array,
10+
* we are checking against all items in the second array.
11+
* The space complexity is O(k) because we are creating a new array to store the common items,
12+
* where k is the number of common items found.
813
* @param {Array} firstArray - First array to compare
914
* @param {Array} secondArray - Second array to compare
1015
* @returns {Array} Array containing unique common items
1116
*/
12-
export const findCommonItems = (firstArray, secondArray) => [
13-
...new Set(firstArray.filter((item) => secondArray.includes(item))),
14-
];
17+
export const findCommonItems = (firstArray, secondArray) => {
18+
const lookup = new Set(secondArray);
19+
const result = new Set();
20+
for (const item of firstArray) {
21+
if (lookup.has(item)) {
22+
result.add(item);
23+
}
24+
}
25+
return [...result];
26+
};

0 commit comments

Comments
 (0)