|
1 | 1 | /** |
2 | 2 | * Finds common items between two arrays. |
3 | | - * |
4 | | - * Time Complexity: |
5 | | - * Space Complexity: |
6 | | - * Optimal Time Complexity: |
7 | | - * |
| 3 | + |
| 4 | + * Inefficiency: the original used secondArray.includes() inside firstArray.filter(), which is a loop inside a loop. |
| 5 | + |
| 6 | + * Originally: |
| 7 | + * Time Complexity: O(n × m) - filter runs n times and each includes call can scan up to m items (O(n²) if the arrays are the same size). |
| 8 | + |
| 9 | + * Space Complexity: O(n) - the filtered array and the Set hold up to n items. |
| 10 | + |
| 11 | + * Optimal Time Complexity: O(n + m) - every item in both arrays must be read at least once |
| 12 | + |
| 13 | + * After refactor (the complexity was reduced from quadratic to linear time by |
| 14 | + using a Set for O(1) average lookups instead of includes): |
| 15 | + |
| 16 | + * Time Complexity: O(n + m) - building secondSet is O(m); the loop over firstArray is O(n) with O(1) average has() checks. |
| 17 | +
|
| 18 | +* Space Complexity: O(n + m) - secondSet holds up to m items; commonElements and the final Set hold up to n items. |
| 19 | +* Optimal Time Complexity: O(n + m) - every item in both arrays must be read at least once, so we can't do better than linear |
| 20 | + * |
8 | 21 | * @param {Array} firstArray - First array to compare |
9 | 22 | * @param {Array} secondArray - Second array to compare |
10 | 23 | * @returns {Array} Array containing unique common items |
11 | 24 | */ |
12 | | -export const findCommonItems = (firstArray, secondArray) => [ |
13 | | - ...new Set(firstArray.filter((item) => secondArray.includes(item))), |
14 | | -]; |
| 25 | +export const findCommonItems = (firstArray, secondArray) => { |
| 26 | +const secondSet = new Set(secondArray); |
| 27 | +let commonElements = []; |
| 28 | + |
| 29 | +for(let ele of firstArray){ |
| 30 | + if(secondSet.has(ele)){ |
| 31 | + commonElements.push(ele); |
| 32 | + } |
| 33 | +} |
| 34 | +return [...new Set(commonElements)]; |
| 35 | +}; |
0 commit comments