-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCheckingSumZero.js
More file actions
45 lines (34 loc) · 954 Bytes
/
CheckingSumZero.js
File metadata and controls
45 lines (34 loc) · 954 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
// Q -> Checking Sum zero and return the first pair
// [-5 , -4 , -3 , -2 , 0 , 2 , 4 , 6 , 8]
// ans -> [-4 , 4]
const arr = [-5, -4, -3, -2, 0, 2, 4, 6, 8];
// first solution with two loops
function findZeroPairWithTwoLoops(arr) {
for (let i in arr) {
for (let j = 1; j < arr.length; j++) {
if (arr[i] + arr[j] === 0) {
return console.log([arr[i], arr[j]]);
}
}
}
}
// call the function
findZeroPairWithTwoLoops(arr);
// second solution with one loop
function findZeroPairWithOneLoop(arr) {
let i = 0;
let j = 1;
let isBreak = true
while (isBreak) {
if (arr[i] + arr[j] === 0) {
console.log([arr[i], arr[j]]);
isBreak = false
} else if (j <= arr.length) {
i++
} else {
j++
}
}
}
// call the function
findZeroPairWithOneLoop(arr);