Skip to content

Commit 7152052

Browse files
committed
Pair With given sum problem
1 parent 3492e78 commit 7152052

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed

PairWithGivenSum.js

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
// Approach 1
2+
function PairWithGivenSum(arr, sum) {
3+
for (let i = 0; i < arr.length; i++) {
4+
for (let j = i + 1; j < arr.length; j++) {
5+
if (arr[i] + arr[j] === sum) {
6+
return true;
7+
}
8+
}
9+
}
10+
return false;
11+
}
12+
13+
const arr = [2, 3, 3, 6];
14+
15+
console.log(PairWithGivenSum(arr, 6));
16+
17+
// Approach 2
18+
19+
function PairWithGivenSum(arr, sum) {
20+
const set = new Set();
21+
for (let i = 0; i < arr.length; i++) {
22+
if (set.has(sum - arr[i])) {
23+
return true;
24+
} else {
25+
set.add(arr[i]);
26+
}
27+
}
28+
return false;
29+
}
30+
31+
const arr = [2, 1, 3, 6];
32+
33+
console.log(PairWithGivenSum(arr, 6));

0 commit comments

Comments
 (0)