Skip to main content

Guidelines

Binary search implementation:

public int search(int[] nums, int target) {
int low = 0, high = nums.length - 1;

while(low <= high){
int mid = low + (high-low)/2; // coping with overflow
if(nums[mid] == target){
return mid;
}
else if(nums[mid] < target){
low = mid + 1;
}
else{
high = mid - 1;
}
}

return -1;
}

Wherever there is a mention of some order (partial or full) or even some kind of releation between successor and predecessor think about how can you eliminate some parts of the search space using (modified) binary search. There are actually only three things you need to get right when implementing binary search:

  • initial boundaries
  • definition of invariants (e.g. while(low <= high))
  • trial function (some calculation to check if the mid is the best element or if and how we should move to left or right in search space)
while(start <= end)  // if you're returning solution from the loop
while(start < end) // if you're returning after the loop
// built in binary search
int idx = Arrays.binarySearch(sums, element); // returns the index of found element or insertion point if not found (negative index)
return idx >= 0 ? idx : ~idx;

// for array of complex objects
int idx = Collections.binarySearch(map.get(key), new Pair("", timestamp), (a, b) -> a.timestamp - b.timestamp);