Skip to content

Commit fb2dd2b

Browse files
committed
--update: find 2 nums that adds upto N
1 parent 06dd311 commit fb2dd2b

File tree

1 file changed

+32
-0
lines changed
  • src/_Problems_/find-2-nums-adding-to-n

1 file changed

+32
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
// the best case using a data structure - SET
2+
function findTwoNumsAddingToN(arr, sum) {
3+
const nums = [];
4+
const store = new Set();
5+
6+
for (let i = 0; i < arr.length; i++) {
7+
// check if the set contains one of the pir that sum upto given sum
8+
if (store.has(sum - arr[i])) {
9+
nums.push(sum - arr[i]);
10+
nums.push(arr[i]);
11+
break;
12+
}
13+
// push the element in the set
14+
store.add(arr[i]);
15+
}
16+
return nums.length ? nums : false;
17+
}
18+
19+
// the Brute force approach
20+
function findTwoNumsAddingToN2(arr, sum) {
21+
const nums = [];
22+
for (let i = 0; i < arr.length; i++) {
23+
for (let j = i + 1; j < arr.length; j++) {
24+
if (arr[i] + arr[j] === sum) {
25+
nums.push(arr[i], arr[j]);
26+
break;
27+
}
28+
}
29+
}
30+
31+
return nums.length ? nums : false;
32+
}

0 commit comments

Comments
 (0)