Modified Binary Search

Binary search beyond "find x" — rotated arrays, peaks, 2D matrices, infinite arrays, and searching the answer space.

Intermediate 2 min readLesson 9 of 25

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.)

InteractiveBinary search
2
0
lo
5
1
8
2
12
3
16
4
23
5
38
6
56
7
72
8
91
9
hi
Search for 23. lo=0, hi=9
1/7
When to use this pattern
  • 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;
}

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.

40516273041526lomidhi
a[lo] ≤ a[mid], so the left half [4..7] is sorted. Target 1 isn't in it → search right.
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];
}

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;
}

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.

Practice problems
  • 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
Key takeaways
  • 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.