Why does mid = (left + right) / 2 fail in Binary Search and how do you fix it?
Quick Summary: In fixed-width signed 32-bit languages (Java/C++), adding left + right when both exceed 1.07 billion overflows Integer.MAX_VALUE negative and crashes indexing; computing left + (right - left) / 2 or (left + right) >>> 1 prevents overflow while keeping O(log n) time.
Direct Interview Answer
Even when an array stays valid within memory, computing (left + right) / 2 sums two indices before dividing—wrapping past 2,147,483,647 into negative integers and throwing ArrayIndexOutOfBoundsException.
Using int mid = left + (right - left) / 2; (or unsigned shift (left + right) >>> 1 in Java) computes the exact midpoint safely for all valid indices.
Detailed Technical Explanation
Pair safe midpoint arithmetic with a strict loop invariant: for inclusive bounds [left, right], use while (left <= right) and always update boundaries by mid + 1 or mid - 1 so the search space shrinks strictly every iteration without infinite loops.
Practical Walkthrough
Canonical overflow-safe Java binary search returning target index or -1.
public class SafeBinarySearch {
public static 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;
}
}
Strict O(log n) time, O(1) space, zero integer overflow risk.
Real-World Production Use Case
Log timestamp bisecting, database B-Tree page search, and capacity optimization problems ("Binary Search on Answer").
Common Interview Mistakes to Avoid
- Writing while (left < right) with right = mid - 1, accidentally skipping the final single element check.
- Using (left + right) / 2 in Java/C++ interviews on large search bounds.