Skip to content

Instantly share code, notes, and snippets.

@kgmorales
Last active October 5, 2020 18:09
Show Gist options
  • Save kgmorales/e34b6d7352564302118145b03f728d0f to your computer and use it in GitHub Desktop.
Save kgmorales/e34b6d7352564302118145b03f728d0f to your computer and use it in GitHub Desktop.
Find the minimum value in that array in O(n) or less.
//Given an array that was once sorted in ascending order is rotated at some pivot unknown to you beforehand (so [0,2,4,7,9] //might become [7,9,0,2,4], for example). Find the minimum value in that array in O(n) or less.
const arr = [7, 9, 0, 2, 4];
const getMinValue = (arr) => {
let left = 1;
let right = arr.length - 1;
let min = arr[0];
while (left < right) {
if (arr[left] < arr[right]) {
min = Math.min(min,arr[left]);
left++;
} else {
min = Math.min(min, arr[right]);
right--;
}
}
return min;
}
getMinValue(arr);
//0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment