Modified Binary Search
Binary search beyond "find x" — rotated arrays, peaks, 2D matrices, infinite arrays, and searching the answer space.
Binary search works whenever you can look at the middle and discard half of the remaining space with certainty. The data doesn't have to be fully sorted; you only need a monotonic property to decide which half survives. (Fundamentals: Searching & binary search.)
- Sorted or rotated sorted input, or a sorted matrix.
- "Find the first/last position", "insertion point", "closest element".
- "Find a peak" or a boundary where a condition flips.
- "Find the minimum value of x such that condition(x) holds" with monotonic condition → search the answer space.
- A required O(log n) bound.
The safe template (first index where the predicate is true)
// Returns the smallest i in [lo, hi] with ok(i) true; hi if none (callers set hi = n)
int firstTrue(int lo, int hi, java.util.function.IntPredicate ok) {
while (lo < hi) {
int mid = lo + (hi - lo) / 2;
if (ok.test(mid)) hi = mid; // mid could be the answer
else lo = mid + 1; // answer is to the right
}
return lo;
}def first_true(lo, hi, ok):
"""Smallest i in [lo, hi) with ok(i); hi if none."""
while lo < hi:
mid = (lo + hi) // 2
if ok(mid):
hi = mid
else:
lo = mid + 1
return lofunction firstTrue(lo: number, hi: number, ok: (i: number) => boolean): number {
while (lo < hi) {
const mid = lo + ((hi - lo) >> 1);
if (ok(mid)) hi = mid;
else lo = mid + 1;
}
return lo;
}Express every problem as a predicate that is false…false true…true and this one template solves it.
Search in a rotated sorted array
[4, 5, 6, 7, 0, 1, 2] — one half around mid is always sorted. Check whether the target lies in that sorted half; if yes go there, otherwise go to the other half.
int searchRotated(int[] a, int target) {
int lo = 0, hi = a.length - 1;
while (lo <= hi) {
int mid = (lo + hi) >>> 1;
if (a[mid] == target) return mid;
if (a[lo] <= a[mid]) { // left half sorted
if (a[lo] <= target && target < a[mid]) hi = mid - 1;
else lo = mid + 1;
} else { // right half sorted
if (a[mid] < target && target <= a[hi]) lo = mid + 1;
else hi = mid - 1;
}
}
return -1;
}
int findMinRotated(int[] a) { // the rotation point
int lo = 0, hi = a.length - 1;
while (lo < hi) {
int mid = (lo + hi) >>> 1;
if (a[mid] > a[hi]) lo = mid + 1; // min is right of mid
else hi = mid;
}
return a[lo];
}def search_rotated(a, target):
lo, hi = 0, len(a) - 1
while lo <= hi:
mid = (lo + hi) // 2
if a[mid] == target:
return mid
if a[lo] <= a[mid]: # left half sorted
if a[lo] <= target < a[mid]:
hi = mid - 1
else:
lo = mid + 1
else: # right half sorted
if a[mid] < target <= a[hi]:
lo = mid + 1
else:
hi = mid - 1
return -1
def find_min_rotated(a):
lo, hi = 0, len(a) - 1
while lo < hi:
mid = (lo + hi) // 2
if a[mid] > a[hi]:
lo = mid + 1
else:
hi = mid
return a[lo]function searchRotated(a: number[], target: number): number {
let lo = 0, hi = a.length - 1;
while (lo <= hi) {
const mid = (lo + hi) >>> 1;
if (a[mid] === target) return mid;
if (a[lo] <= a[mid]) {
if (a[lo] <= target && target < a[mid]) hi = mid - 1;
else lo = mid + 1;
} else {
if (a[mid] < target && target <= a[hi]) lo = mid + 1;
else hi = mid - 1;
}
}
return -1;
}Find a peak element
A peak is greater than its neighbours. If a[mid] < a[mid + 1], the slope rises to the right, so a peak must exist on the right; otherwise one exists at mid or to its left. O(log n) even though the array isn't sorted.
int findPeak(int[] a) {
int lo = 0, hi = a.length - 1;
while (lo < hi) {
int mid = (lo + hi) >>> 1;
if (a[mid] < a[mid + 1]) lo = mid + 1; // climb uphill
else hi = mid;
}
return lo;
}def find_peak(a):
lo, hi = 0, len(a) - 1
while lo < hi:
mid = (lo + hi) // 2
if a[mid] < a[mid + 1]:
lo = mid + 1
else:
hi = mid
return lofunction findPeak(a: number[]): number {
let lo = 0, hi = a.length - 1;
while (lo < hi) {
const mid = (lo + hi) >>> 1;
if (a[mid] < a[mid + 1]) lo = mid + 1; else hi = mid;
}
return lo;
}2D matrices
- Rows sorted and each row starts after the previous row ends: treat it as one flat sorted array of length R·C; index k maps to
(k / C, k % C). O(log(RC)). - Rows and columns sorted independently: start at the top-right corner; if the value is too big move left, too small move down. O(R + C) — a "staircase" search, not binary search.
Binary search on the answer
"Minimise the maximum" or "find the smallest capacity/speed/days" — if feasibility is monotonic, binary search the value and test feasibility greedily. Examples: Koko eating bananas, capacity to ship packages within D days, split array largest sum, minimum days to make bouquets, aggressive cows. Full walkthrough in Searching.
- Binary Searcheasy
- Search Insert Positionlower boundeasy
- First Bad Versionfirst trueeasy
- Find First and Last Position of Elementmedium
- Search in Rotated Sorted Arraymedium
- Find Minimum in Rotated Sorted Arraymedium
- Find Peak Elementmedium
- Search a 2D Matrixmedium
- Koko Eating Bananasanswer spacemedium
- Capacity To Ship Packages Within D Daysmedium
- Time Based Key-Value Storeupper bound on timestampsmedium
- Split Array Largest Sumhard
- Median of Two Sorted Arrayspartition search, O(log min(m,n))hard
- Binary search needs a decision that safely discards half — not necessarily a sorted array.
- Use one "first true" template with
lo < hi,hi = mid,lo = mid + 1. - Rotated arrays: one half around mid is always sorted.
- Peaks: move toward the rising neighbour.
- Optimisation with monotonic feasibility → binary search the answer.