-
Notifications
You must be signed in to change notification settings - Fork 0
/
sumZero.js
53 lines (44 loc) · 1.15 KB
/
sumZero.js
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
46
47
48
49
50
51
52
53
/*
Write a function called sumZero which accepts a sorted array of integers. The function should find the first pair where the sum is 0. Return an array that includes both values that sum to zero or undefined if a pair does not exist
sumZero([-3,-2,-1,0,1,2,3]) // [-3,3]
sumZero([-2,0,1,3]) // undefined
sumZero([1,2,3]) // undefined
*/
//brute force
function sumZero(arr) {
if (arr.length >= 2) {
for (let i = 0; i < arr.length; i++) {
const current = arr[i];
const opposite = -current;
if (arr.includes(opposite)) {
return [current, opposite];
}
}
}
return undefined;
}
function sumZero(arr) {
for (let i = 0; i < arr.length; i++) {
for (let j = i + 1; j < arr.length; j++) {
if (arr[i] + arr[i] === 0) {
return [arr[i], arr[j]];
}
}
}
}
//refactored
function sumZero(arr){
let left = 0;
let right = arr.length - 1;
while(left < right){
let sum = arr[left] + arr[right]
if(sum === 0){
return [arr[left], arr[right]]
}else if(sum > 0){
right--
}else{
left++
}
}
}
sumZero([-4,-3,-2,-1,0,1,2,3,10])