Binary search · Easy
Binary Search: the idea to remember.
Locate a target in a sorted array of distinct integers, returning its index or negative one.
The core insight
Keep a closed candidate interval and discard the midpoint after a failed comparison.
Why it works
If the target exists it remains inside [left, right]. Each failed comparison strictly shortens the interval.
The mistake to avoid
Using left = mid can stall on a two element interval.
Time: O(log n)Space: O(1)
Commented Java solution
Use java.util.* imports and a surrounding solution class. Tree snippets assume the standard TreeNode definition; linked lists use ListNode and Clone Graph uses a Node with val and neighbors; Copy Random List uses Node with val, next and random. Read the input assumptions above.
int search(int[] nums, int target) {
int left = 0, right = nums.length - 1;
while (left <= right) {
int mid = left + (right - left) / 2;
if (nums[mid] == target) return mid;
if (nums[mid] < target) left = mid + 1;
else right = mid - 1;
}
return -1;
}Make the next connection
Independent revision notes with credited Java references. Not affiliated with LeetCode or the source sheets.