Binary Search Target Index
Given a sorted array of integers and a target value, return the index where the target appears. If the target is not present in the array, return -1. This is the classic binary search problem.
Because the array is sorted, you do not need to scan it from left to right. Instead, compare the target with the middle element: if they match, the middle index is the answer. If the target is smaller than the middle element, the answer must lie in the left half. If it is larger, the answer lies in the right half. Each comparison eliminates roughly half of the remaining search space.
For example, if nums = [-1,0,3,5,9,12] and target = 9, the answer is 4. The search compares 9 with 3 (mid), moves right, then compares 9 with 9 (mid), and returns 4. If target = 2, the search narrows down but never finds 2, so it returns -1. An empty array always returns -1 because there is nowhere to look.
Binary search is one of the most important algorithms in computer science. It appears in database index lookups, sorted-map operations, and any problem where the search space can be halved. Understanding it is a prerequisite for more advanced search problems like finding boundaries, first/last occurrences, and the insert position.
Edge cases include an empty array (return -1), a single-element array (return 0 if it matches, otherwise -1), the target being the smallest or largest element (return 0 or the last index), and the target appearing more than once (return any one of its indices — the classic problem returns the first one found).
Example Input & Output
The target value 2 is not present in the array, so return -1.
The array is empty, so return -1.
The target value 9 is found at index 4 in the array.
Algorithm Flow
Solution Approach
Maintain two pointers, left and right, that define the current search range. Compute the middle index and compare the middle value with the target to decide which half to keep.
If nums[mid] equals the target, return mid immediately. If it is smaller, the target must be to the right, so set left = mid + 1. If it is larger, set right = mid - 1. When the loop exits without returning, the target is not in the array, so return -1.
Time complexity is O(log n), space complexity is O(1).
Best Answers
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;
}
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
