Easy templates for Binary Search for Interview

Template 1

Find target

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

Template 2

Find first occurrence of the target

public int binarySearch(int[] nums, int target) {
    int left = 0, right = nums.length - 1;
    while (left <= right) {
        int mid = left + (right - left) / 2;
        if (target > nums[mid]) left = mid + 1;
        else if (target < nums[mid]) right = mid - 1;
        else if (target == nums[mid]) right = mid - 1;
    }
    if (left >= nums.length || nums[left] != target) return -1;
    return left;                                                
}

Template 3

Find last occurrence of the target

public int binarySearch(int[] nums, int target) {
    int left = 0, right = nums.length - 1;
    while (left <= right) {
        int mid = left + (right - left) / 2;
        if (target > nums[mid]) left = mid + 1;
        else if (target < nums[mid]) right = mid - 1;
        else if (target == nums[mid]) left = mid + 1;
    }
    if (right < 0 || nums[right] != target) return -1;
    return right;                                                
}
Comments (0)