|
1 | 1 | /** |
2 | 2 | * Finds common items between two arrays. |
3 | 3 | * |
4 | | - * Time Complexity: O(n * m) |
5 | | - * Space Complexity: O(n) |
6 | | - * Optimal Time Complexity: O(n + m) |
| 4 | + * Time Complexity: O(n + m) |
| 5 | + * Space Complexity: O(n + m) |
7 | 6 | * |
8 | 7 | * @param {Array} firstArray - First array to compare |
9 | 8 | * @param {Array} secondArray - Second array to compare |
10 | 9 | * @returns {Array} Array containing unique common items |
11 | 10 | */ |
12 | 11 |
|
13 | | -export const findCommonItems = (firstArray, secondArray) => [ |
14 | | - ...new Set(firstArray.filter((item) => secondArray.includes(item))), |
15 | | -]; |
16 | | - |
17 | | -// Time complexity is O(n * m) because for each item in the first array, |
18 | | -// includes() may search through the entire second array. |
19 | | - |
20 | | -// Space complexity is O(n) because filter() creates a new array |
21 | | -// and Set stores unique common items. |
22 | | - |
23 | | -// Optimal time complexity is O(n + m) because using Sets |
24 | | -// allows us to check for common items more efficiently. |
25 | 12 | export function findCommonItems(firstArray, secondArray) { |
| 13 | + const firstSet = new Set(firstArray); |
26 | 14 | const secondSet = new Set(secondArray); |
27 | | - const commonItems = new Set(); |
28 | 15 |
|
29 | | - for (const item of firstArray) { |
30 | | - if (secondSet.has(item)) { |
31 | | - commonItems.add(item); |
32 | | - } |
33 | | - } |
34 | | - |
35 | | - return [...commonItems]; |
| 16 | + return [...firstSet.intersection(secondSet)]; |
36 | 17 | } |
37 | | - |
38 | | -// Time complexity: O(n + m) |
39 | | -// Space complexity: O(n + m) |
40 | | -// Optimal time complexity: O(n + m) |
0 commit comments