BudiBadu Logo

Binary Search Target Index

Binary Search Easy 65 views
Like9

Binary Search Target Index is about finding a target value inside a sorted integer array as efficiently as possible. Instead of scanning linearly, you repeatedly split the search range in half using left, right, and mid pointers. If the mid value matches the target, return that index. If target is smaller, move right boundary left; if larger, move left boundary right.

The expected output is an integer index when found, or -1 when the target does not exist. In this dataset, the judge may include repeated values in some tests, so your implementation should still return a valid index where the target appears, not necessarily a specific first or last occurrence unless explicitly required.

Edge handling matters: empty arrays should return -1, and pointer updates must avoid infinite loops. Keep the logic deterministic and avoid extra print output, because the checker evaluates only your returned index. This problem trains core interview fundamentals: boundary control, condition branching, and confidence with logarithmic-time search.

Examples

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 - Budibadu
Recommendation Algorithm Flow for Binary Search Target Index - Budibadu

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;
    }
}