Skip to content

Commit 749e9e0

Browse files
committed
Refactor hasPairWithSum from O(n²) to O(n) using a Set
1 parent b538892 commit 749e9e0

1 file changed

Lines changed: 31 additions & 9 deletions

File tree

Lines changed: 31 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,21 +1,43 @@
11
/**
22
* Find if there is a pair of numbers that sum to a given target value.
33
*
4-
* Time Complexity:
5-
* Space Complexity:
6-
* Optimal Time Complexity:
4+
* Inefficiency: the original used a loop inside a loop to check every
5+
* possible pair of numbers.
6+
*
7+
* Originally:
8+
* Time Complexity: O(n²) - for each number, the inner loop scans the
9+
* remaining numbers, so about n * (n - 1) / 2 pair checks.
10+
*
11+
* Space Complexity: O(1) - only the loop counters i and j are used.
12+
*
13+
* Optimal Time Complexity: O(n) - every number must be read at least once,
14+
* and a Set gives O(1) average lookups, so one pass is enough
15+
*
16+
* After Refactor (reduced from quadratic to linear time by remembering the
17+
* numbers already seen in a Set instead of re-scanning the list):
18+
*
19+
* Time Complexity: O(n) - one loop, with O(1) average has() and add().
20+
*
21+
* Space Complexity: O(n) - visitedNumbers can hold up to n numbers.
22+
*
23+
* Optimal Time Complexity: O(n) - every number must be read at least once,
24+
* so we can't do better than linear.
725
*
826
* @param {Array<number>} numbers - Array of numbers to search through
927
* @param {number} target - Target sum to find
1028
* @returns {boolean} True if pair exists, false otherwise
1129
*/
1230
export function hasPairWithSum(numbers, target) {
13-
for (let i = 0; i < numbers.length; i++) {
14-
for (let j = i + 1; j < numbers.length; j++) {
15-
if (numbers[i] + numbers[j] === target) {
16-
return true;
17-
}
31+
const visitedNumbers = new Set();
32+
33+
for (let num of numbers) {
34+
const partnerNum = target - num;
35+
36+
if (visitedNumbers.has(partnerNum)) {
37+
return true;
1838
}
39+
visitedNumbers.add(num);
1940
}
41+
2042
return false;
21-
}
43+
}

0 commit comments

Comments
 (0)