|
1 | 1 | /** |
2 | 2 | * Finds common items between two arrays. |
3 | 3 | * |
4 | | - * Time Complexity: |
5 | | - * Space Complexity: |
6 | | - * Optimal Time Complexity: |
| 4 | + * Time Complexity: O(n*m) where n and m are length of each array |
| 5 | + * Space Complexity: O(n) where n is a length of arrays |
| 6 | + * Optimal Time Complexity: O(n) |
7 | 7 | * |
8 | 8 | * @param {Array} firstArray - First array to compare |
9 | 9 | * @param {Array} secondArray - Second array to compare |
10 | 10 | * @returns {Array} Array containing unique common items |
11 | 11 | */ |
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 | + // program flow: |
| 15 | + // firstArray.filter go through the each item in first array (loop) |
| 16 | + // secondArray.includes check if that item is in the second array (nested loop) |
| 17 | + // nested loop result in O(n^2) time complexity |
| 18 | + |
| 19 | + // to reduce time complexity to sublinear on the number of elements in the arrays we can use Set and it's .intersection() method |
| 20 | + |
| 21 | + // complexity of this operation is O(n) |
| 22 | + const firstArraySet = new Set(firstArray); |
| 23 | + // complexity of this operation is O(m) |
| 24 | + const secondArraySet = new Set(secondArray); |
| 25 | + // intersection method uses has method which is considered to be faster than O(n) and since JS uses hash tables for has methods, the complexity should be |
| 26 | + // has O(1) and intersection O(n) which result in O(n) overall time complexity |
| 27 | + return Array.from(firstArraySet.intersection(secondArraySet)); |
| 28 | +}; |
0 commit comments