11/**
22 * Finds common items between two arrays.
3- *
4- * Time Complexity:
5- * Space Complexity:
6- * Optimal Time Complexity:
3+ *
4+ * Time Complexity: O(n * m)
5+ * Space Complexity: O(n)
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
11- *
12- * Time Complexity: O(n * m)
13- * Space Complexity: O(u)
14- * Optimal Time Complexity: O(n + m)
1511 */
1612export const findCommonItems = ( firstArray , secondArray ) => {
1713 const allowedItems = new Set ( secondArray ) ;
@@ -24,6 +20,13 @@ export const findCommonItems = (firstArray, secondArray) => {
2420
2521console . log ( findCommonItems ( [ 2 , 5 , 7 ] , [ 5 , 6 , 7 ] ) ) ;
2622
27- // Time:O(n \ m) filter() visits each item in the first array, and includes() may scan the second array each time.
28- // Sace: O(k) The Set stores unique common items, and the resulting array contains those items.
29- // Optimal time: O(n+m) Achievable on average using a Set for efficient lookups.
23+
24+ // Time Complexity: O(n + m) on average.
25+ // Building the Set takes O(m), and filtering the first array takes O(n)
26+ // on average because Set.has() provides efficient lookups.
27+
28+ // Space Complexity: O(n + m).
29+ // The Set stores elements from secondArray, while the filter result
30+ // and the Set of unique common items require additional space.
31+
32+ // Improvement: Reduces average time complexity from O(n * m) to O(n + m).
0 commit comments