JSFiddle - React, Tailwind, and code Playground
by asdf
JavaScript
// You have a sorted array of distinct integers. Find the element where the array index is equal to the value of the corresponding element. Or return that no such element exists.
function getIndexElm(arr) {
if (arr[0] > arr.length) {
return;
}
var start = 0;
var end = arr.length-1;
var mid, dif;
while (start <= end) {
mid = Math.floor((end - start)/2 + start);
dif = arr[mid] - mid;
if (dif === 0) {
return mid;
}
if (dif > 0) {
end = mid - 1;
} else {
start = mid + 1;
}
}
return -1;
}
console.log(getIndexElm([-1, 0, 2, 4, 5, 8, 12]));
console.log(getIndexElm([1, 2, 4, 5, 8, 12]));