Binary Search · Pattern 3 of 8

Binary search on a condition: first true

No target value at all: binary search the first index where a yes/no condition becomes true. A bad version, an index-parity break or a downhill slope.

3 variations · 3 problems · 3 with animated walkthroughs

Watch the lesson

Concepts first, then the problem and every approach, step by step.

Space to play or pause · ← → to jump a step · click or drag the bar to seek

When to use it

  • Everything before some point is "good" and everything after is "bad"
  • Pairs or a pattern break at exactly one place
  • Any peak, valley or turning point is acceptable

The template

Unique 1-D Binary Search
// first x in [lo, hi] where ok(x) is true
// ok must look like: false, false, ..., true, true
int firstTrue(int lo, int hi) {
    while (lo < hi) {
        int mid = lo + (hi - lo) / 2;
        if (ok(mid)) hi = mid;      // mid might be the first true
        else lo = mid + 1;          // the first true is right of mid
    }
    return lo;                      // check ok(lo) if a true might not exist
}

// peak element: ok(i) = a[i] > a[i + 1], searched over [0, n - 1]

The variations

  1. 1A yes/no check

    The condition is given to you as an API call. Binary search the first version where it says yes, and count the calls: that is what the interviewer is grading.

  2. 2Index parity

    Before the single element, pairs start at even indexes; after it, at odd ones. Check the pair at an even mid to see which side you are on.

  3. 3Slope: find a peak

    If a[mid] < a[mid + 1] you are walking uphill, so a peak is to the right. Otherwise one is at mid or to the left. Any peak counts.

Mistakes to avoid

  • Writing a condition that is not monotonic: test it on a small array by hand first.
  • For the peak, comparing a[mid] with a[mid + 1] when mid can be the last index. Searching [0, n - 1] with lo < hi keeps mid + 1 in range.
Next: Rotated sorted arrays →

Mark it done once you can write the template from memory and you have solved the worked examples yourself.