LeetCode 704 Binary Search - Solution

The core idea

Compare the middle element to the target. If they match, return the index. If target is smaller, search the left half. If larger, search the right half.

Set two pointers: left = 0 and right = n - 1. Compute mid = (left + right) / 2. Based on the comparison, either return mid or adjust one of the bounds.

With nums = [-1, 0, 3, 5, 9, 12] and target = 9: start with left = 0, right = 5. Mid is index 2, value 3. Since 9 > 3, search right: left = 3. Mid is index 4, value 9. Found it.

Each comparison cuts the search space in half. This is the foundation of all binary search problems.