Skip to content

Commit 8e24202

Browse files
answered JS find common items
1 parent 4a33688 commit 8e24202

File tree

1 file changed

+42
-6
lines changed

1 file changed

+42
-6
lines changed
Lines changed: 42 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,50 @@
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)
5+
* Space Complexity: O(M)
6+
* Optimal Time Complexity: O(N + M)
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+
// 1. Create a Set from the second array. (O(M) time)
14+
// This allows for O(1) average time lookups using the has() method,
15+
// as per the typical performance characteristics of Set.
16+
const secondSet = new Set(secondArray);
17+
18+
// 2. Filter the first array (O(N) time) using O(1) lookups.
19+
// The filter uses Set.prototype.has() for O(1) average time complexity.
20+
// The overall time complexity for the filter step becomes O(N * 1) = O(N).
21+
const commonItems = firstArray.filter((item) => secondSet.has(item));
22+
23+
// 3. Use a final Set to guarantee unique results (O(N) time) and return an array.
24+
return [...new Set(commonItems)];
25+
};
26+
27+
/*
28+
Explanation:
29+
The function first creates a Set from the second array, which takes O(M) time,
30+
where M is the length of the second array. This allows for O(1) average time
31+
lookups when checking for common items.
32+
33+
Next, it filters the first array, which takes O(N) time, where N is the length
34+
of the first array. Each lookup in the Set is O(1) on average, so the overall
35+
time complexity for this step remains O(N).
36+
37+
Finally, to ensure that the result contains only unique items, a new Set is
38+
created from the filtered results, which also takes O(N) time in the worst case.
39+
Converting this Set back to an array is also O(N).
40+
41+
Overall, the total time complexity is O(N + M), which is optimal for this problem,
42+
as each element from both arrays must be examined at least once.
43+
44+
Space Complexity:
45+
The space complexity is O(M) due to storing the second array in a Set.
46+
The additional space used for the result array is O(K), where K is the number
47+
of unique common items, but this is typically less than or equal to M.
48+
49+
Source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set
50+
*/

0 commit comments

Comments
 (0)