Skip to content

Commit ca928df

Browse files
committed
Optimize hasPairWithSum using a Set
1 parent 7928c48 commit ca928df

2 files changed

Lines changed: 18 additions & 11 deletions

File tree

Lines changed: 14 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,13 @@
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
*/
1612
export const findCommonItems = (firstArray, secondArray) => {
1713
const allowedItems = new Set(secondArray);
@@ -24,6 +20,13 @@ export const findCommonItems = (firstArray, secondArray) => {
2420

2521
console.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).

‎Sprint-1/JavaScript/hasPairWithSum/hasPairWithSum.js‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,3 +26,7 @@ export function hasPairWithSum(numbers, target) {
2626
return false;
2727

2828
}
29+
30+
31+
// Time Complexity: O(n) We check each number once.
32+
// Space Complexity: O(n) The Set may store all n numbers.

0 commit comments

Comments
 (0)