Skip to content

Instantly share code, notes, and snippets.

@Jimmydalecleveland
Last active June 12, 2019 15:04
Show Gist options
  • Save Jimmydalecleveland/0c9e79a3f851eac9912ea388b2202e51 to your computer and use it in GitHub Desktop.
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
/* 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