Template 4; made initial condition of Template 2 same as that of Template 1 & 3
public int search(int[] nums, int target) {
      if(nums == null || nums.length == 0)
        return -1;

      int left = 0, right = nums.length - 1; //in Template 2 right = nums.length
      while(left < right){
        // Prevent (left + right) overflow
        int mid = left + (right - left) / 2;
        if(nums[mid] == target){ return mid; }
        else if(nums[mid] < target) { left = mid + 1; }
        else { right = mid; }
      }

      // Post-processing:
      // End Condition: left == right
      if(nums[left] == target) return left; //Removing left != nums.length && from here
      return -1;
        
    }

This is updated template 2.

It uses the same initial condition as other two templates which is

	left = 0, right = nums.length - 1;

By doing so, it does not distract the reader/programmer by taking it's attention to initial condition rather brings back the attention to termination condition which is the sole difference between the original 3 candidates.

So, this can be made the accepted template 2 and hence the users will be able to better remember the templates.

Comments (2)