Skip to content

Commit 08996f8

Browse files
committed
haspairwithsum func complexity analysis + refactoring for better efficiency
1 parent ced4ca0 commit 08996f8

File tree

1 file changed

+27
-5
lines changed

1 file changed

+27
-5
lines changed

Sprint-1/JavaScript/hasPairWithSum/hasPairWithSum.js

Lines changed: 27 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -9,13 +9,35 @@
99
* @param {number} target - Target sum to find
1010
* @returns {boolean} True if pair exists, false otherwise
1111
*/
12+
// 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+
// }
18+
// }
19+
// }
20+
// return false;
21+
// }
22+
23+
//My Analysis Result
24+
// Time Complexity - since it have two nested loop of the same size/growth here i have a growth of O(n * n) = O(n**2) .. quadratic growth
25+
// Space Complexity - I didnt see any assigning/modifying stored data scenario so i think the space complexity is just O(1) for the return statement
26+
//The inefficiency of this program is due to the nested loop : it creates redudndant checks to compare the numbers.
27+
28+
//here is the refactored code avoiding that redundancy
29+
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 seenNumbers = new Set();
32+
for (const num of numbers) {
33+
const complement = target - num;
34+
if (seenNumbers.has(complement)) {
35+
return true; // We found a pair!
1836
}
37+
seenNumbers.add(num);
1938
}
2039
return false;
2140
}
41+
//here time complexity is reduced to optimal level . just one loop which is O(n)
42+
//for the space complexity here i have O(n) as well because of the Set() i used.
43+
//i traded space to have an optimal time complexity

0 commit comments

Comments
 (0)