Last active
June 12, 2019 15:04
-
-
Save Jimmydalecleveland/0c9e79a3f851eac9912ea388b2202e51 to your computer and use it in GitHub Desktop.
Given an array of sorted numbers, find the first 2 values that equal zero
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* Inefficient example would be a nested loop -- O(n^2) | |
** Below version uses multiple pointers to achieve O(n) | |
*/ | |
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]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment