Binary Search is a divide-and-conquer algorithm that finds the position of a target value within a sorted array. It works by repeatedly dividing the search interval in half.
However, advanced Binary Search isn't just for finding elements. It's used to Binary Search on an Answer—finding the optimal value that satisfies a monotonic condition.
Look for these signals:
-
"Sorted Array" + require
$O(\log N)$ Time: This is a direct mandate to use Binary Search. - "Find the Minimum/Maximum" optimal value: e.g., "minimum capacity to ship within D days". This hints at Binary Search on the Answer.
-
Monotonic functions: If a state flips from
FalsetoTrueat an exact threshold, and staysTrueforever after, you can binary search for that boundary.
Instead of a linear scan
- Find Target in Sorted Array: The classic implementation. Master the
while (L <= R)template. - Search Insert Position: Finding the exact insertion point (usually returning
L). - Search in Rotated Sorted Array: Binary search with an extra
ifcondition to determine which half is properly sorted.
- Find Minimum in Rotated Sorted Array: A variation of the rotated logic focused on finding the pivot point.
- Single Element in Sorted Array: Binary searching based on even/odd index pairs rather than values.
- Koko Eating Bananas: The gateway to "Binary Search on Answer". Here, your array is the range of possible eating speeds
[1, max(piles)].
- Split Array Largest Sum: Binary searching a theoretical answer (the max sum).
- Find in Mountain Array: Ternary search concepts mapped to Binary Search (finding the peak, then searching the slopes).
-
Median of Two Sorted Arrays: Finding a partition point across two arrays simultaneously in
$O(\log(\min(N,M)))$ .
If the search space is large (check(mid) function first, then wrap the template around it.