Logic behind binary search is :
Find the left and right position of heater which best suits a particular house.
Now, consider that if we are given sorted numbers and you have to find a value in that you will use binary search.
Same goes over here, you are given sorted numbers in terms of heater positions and search value is particular house position . Now, you have to find an index of heater position value which is nearest to this house position.
Example :
heaters[] = {1,2,3,8} house_position = 5.
So, closest value of heater from left is 3 (index = 2) which we can find by binary search . Now, this is left position of heater which can heat this house. Right positioned heater can also heat the house which is at next index(index=3) whose value is 8. So, this particular house can be heated by both heaters at position 3 and 8. Out of this we will find best heater position which has minimum distance from the house (since that will have minimum radius). In this case it is heater at position 3(index=2), whose distance from house is 2.
This is the logic of binary search for this question.
Here is the working example of the same (JAVA code).
/**
* @param {number[]} houses
* @param {number[]} heaters
* @return {number}
*/
var findRadius = function(houses, heaters) {
var totalhouses = houses.length, totalheaters = heaters.length, index=0, currindex=0, max = 0, currmin;
heaters.sort((a, b) => a - b);
while(index< totalhouses) {
currindex = search(heaters, houses[index], 10);
if(currindex==-1) { //if left positioned heater is not present
currmin = heaters[0] - houses[index];
} else {
if(currindex+1 < totalheaters) {
currmin = Math.min(heaters[currindex+1] - houses[index], houses[index] - heaters[currindex]);
} else { //if right positioned heater is not present
currmin = houses[index] - heaters[currindex];
}
}
max = Math.max(max, currmin);
index++;
}
return max;
};
var search = function(heaters, value) { //binary search to find best possible left positioned heater for the house
var start=0,end = heaters.length-1, mid=0;
while(start<=end) {
mid = Math.floor((start + end) / 2);
if(heaters[mid] == value){
return mid;
} else if(heaters[mid] > value) {
end = mid-1;
} else {
start = mid+1;
}
}
return end;
}