Code Logo

Binary Search Target Index

Published at05 Jan 2026
Easy 74 views
Like9

This is the standard binary search problem: given a sorted array and a target value, return the index where the target appears.

If the target is not in the array, return -1. Because the array is sorted, you do not need to scan from left to right. You can compare with the middle value and throw away half of the search space each time.

For example, if nums = [-1,0,3,5,9,12] and target = 9, the answer is 4. If target = 2, the answer is -1 because 2 does not appear anywhere in the array.

So the task is to search the sorted array efficiently and return the target's index, or -1 if it does not exist.

Example Input & Output

Example 1
Input
nums = [-1,0,3,5,9,12], target = 2
Output
-1
Explanation

The target value 2 is not present in the array, so return -1.

Example 2
Input
nums = [], target = 5
Output
-1
Explanation

The array is empty, so return -1.

Example 3
Input
nums = [-1,0,3,5,9,12], target = 9
Output
4
Explanation

The target value 9 is found at index 4 in the array.

Algorithm Flow

Recommendation Algorithm Flow for Binary Search Target Index
Recommendation Algorithm Flow for Binary Search Target Index

Solution Approach

The idea behind binary search is simple: compare the target with the middle value, then keep only the half where the target could still exist.

If nums[mid] === target, we are done. If nums[mid] < target, the target must be on the right. If nums[mid] > target, the target must be on the left.

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

while (left <= right) {
  const mid = Math.floor((left + right) / 2);
  if (nums[mid] === target) return mid;
  if (nums[mid] < target) {
    left = mid + 1;
  } else {
    right = mid - 1;
  }
}

If the loop finishes without finding the target, then it is not in the array, so return -1.

This runs in O(log n) time and uses O(1) extra space.

Best Answers

java
class Solution {
    public int search(Object nums, Object target) {
        int[] arr = (int[]) nums;
        int t = (int) target;
        int left = 0;
        int right = arr.length - 1;
        
        while (left <= right) {
            int mid = left + (right - left) / 2;
            if (arr[mid] == t) {
                return mid;
            } else if (arr[mid] < t) {
                left = mid + 1;
            } else {
                right = mid - 1;
            }
        }
        return -1;
    }
}