skip to content

Why can't binary search find a unimodal cost curve's minimum, and what does ternary search do instead?

level: juniorimportance: should knowfreq 32%

answer

  1. Ask what one probe actually tells you
  2. Monotone test is the missing precondition
  3. A valley reads the same on both slopes
  4. Two probes, compare, drop an outer third
  5. Each step keeps two-thirds

basics

~20 s

Binary search needs a monotone test, and one probe on a fall-then-rise curve cannot say which side the minimum is on. Ternary search compares two interior probes to discard the outer third that provably cannot contain it.

solid answer

~40 s

Binary search works when a single probe splits the domain: the value at the midpoint tells you which half to keep, because the ordering is monotone. A unimodal cost curve — say job runtime against batch size, high on the left from per-batch overhead, high on the right from memory pressure, with one minimum in between — is not monotone, so one measurement is ambiguous: the same runtime occurs on both slopes. Ternary search fixes that by taking two interior probes, `m1 = lo + (hi-lo)/3` and `m2 = hi - (hi-lo)/3`. If `f(m1) > f(m2)` the minimum must be right of `m1`, so `lo = m1`; otherwise it is left of `m2`, so `hi = m2`. Each step costs two evaluations and keeps two-thirds of the interval, which still converges logarithmically.

go deeper

for a junior

Be ready to say what unimodal means in one sentence, why one probe is ambiguous on such a curve, and what the two probes let you discard. Knowing the shrink is to two-thirds, not one-third, already puts you ahead.

for a middle

Explain the elimination as an argument, not a recipe: state which third goes for each comparison outcome and why the alternative is impossible. Be able to name the cost — two evaluations per step, logarithmic in the range.

for a senior

Show that you check the precondition before reaching for the technique. Interviewers want to hear you justify unimodality from the shape of the cost model, and name what happens — a silently wrong answer — when the curve has a second local optimum.

for a principal

Frame it as an optimisation tool over a knob, not a lookup. Own the judgment of when a logarithmic probe search is worth it at all versus a coarse sweep, given how expensive one evaluation of the cost is and how confident you are in the curve's shape.

## The precondition, stated precisely Binary search does not really require a sorted array — it requires a **monotone predicate** over the domain: some test that is false everywhere up to a crossover point and true everywhere after it. One probe evaluates that predicate and eliminates one side. Sortedness is just the most familiar way to get monotonicity. A **unimodal** function has no such predicate for its optimum. Take the curve you get from tuning a single knob — total runtime of a batched job as a function of batch size. Tiny batches pay fixed per-batch overhead thousands of times, so runtime is high on the left. Huge batches spill working memory and thrash, so runtime is high on the right. Somewhere in the middle sits one minimum. Formally, for a minimum, unimodal means: there is a point `x*` such that `f` is strictly decreasing on `[lo, x*]` and strictly increasing on `[x*, hi]`. (The mirror definition — rise then fall — gives a maximum; the algorithm is the same with the comparison flipped.) Now ask what one probe buys you. You measure runtime at some batch size and get 40 seconds. Is the minimum to the left or the right? Unanswerable: 40 seconds occurs once on the falling side and once on the rising side, and a single value cannot distinguish them. There is no monotone predicate to split on, so binary search over the *values* has nothing to bite on. ## The two-probe rule Ternary search restores a decidable test by taking **two** interior probes instead of one. Split the current interval `[lo, hi]` into thirds: - `m1 = lo + (hi - lo) / 3` - `m2 = hi - (hi - lo) / 3`, so `lo < m1 < m2 < hi` Compare `f(m1)` against `f(m2)`: - If `f(m1) > f(m2)`, the minimum lies strictly right of `m1`. Set `lo = m1`. - If `f(m1) < f(m2)`, the minimum lies strictly left of `m2`. Set `hi = m2`. - If they are equal *and* the function is strictly unimodal, the minimum lies strictly between them, so both outer thirds can go. The elimination is a contradiction argument, not a heuristic. Suppose `f(m1) > f(m2)` but the minimum sat at or left of `m1`. Then the whole span from `m1` to `m2` lies on the rising side, which forces `f(m1) < f(m2)` — contradicting what you measured. So the assumption is impossible and the left third is safe to drop. ## What it costs Each step discards one third and **keeps two-thirds**, at the price of two evaluations. The name misleads people here: ternary search does not cut the interval to a third. After `k` steps the interval is `(2/3)^k` of its original width, so reaching a target precision takes about `log(range/eps) / log(1.5)` steps — roughly 1.7 steps per halving, at two evaluations each. It is still logarithmic in the range, with a worse constant than binary search. ## Terminating On a continuous domain you cannot land exactly on the optimum; you shrink until the interval is smaller than a tolerance, or simply run a fixed number of iterations chosen so that `(2/3)^k` times the starting width is below what you care about, and return the interval's midpoint. On an integer domain — batch sizes are integers — the probes eventually collide or stop moving, so the usual practice is to loop while the window holds more than about three candidates and then evaluate those directly. ## Where it actually applies Ternary search is not a container-search technique; it is an optimisation technique over a domain you can evaluate a cost at. That domain can be real-valued (a threshold, a ratio, a physical position) or integral (a batch size, a worker count, a chunk width). What it always needs is that the cost genuinely has **one** turning point over the interval you search. If the cost curve has two local minima, the two-probe comparison can eliminate the third containing the global one and you will confidently return the wrong knob value with no error signal at all. ## The common mistakes Three misreadings dominate. First, thinking ternary search finds a *value* the way binary search finds a key — it finds an **extremum's location**, and there is no target to match. Second, thinking it converges faster because "three beats two" — it keeps more of the interval per step, not less. Third, applying it to any curve that looks bumpy: unimodality is a precondition you must justify from the shape of the cost model, not something the algorithm checks for you.

  • Does ternary search work for a maximum as well as a minimum?
    Yes — flip the comparison. For a maximum on a rise-then-fall curve, `f(m1) < f(m2)` means the peak is right of `m1`, so you move `lo` up; otherwise you move `hi` down to `m2`. The precondition is the mirror image: strictly increasing to a single peak, then strictly decreasing. Everything else — the 2/3 shrink, the two evaluations per step, the termination rule — is unchanged.
  • What happens if you run it on a curve with two separate local minima?
    It returns a wrong answer silently. The elimination argument depends on there being exactly one turning point; with two valleys, a comparison between the two probes can favour the shallower one and discard the third holding the global minimum. Nothing in the algorithm detects this — no invariant is violated at runtime. You must justify unimodality from the cost model itself, or sample coarsely first to check the shape.
  • Do the probes have to be at exactly the one-third points?
    No. Any two interior points `m1 < m2` make the comparison valid; the thirds just balance how much you discard in the two cases. Placing them closer together discards nearly half each step but converges slowly when they are too close, and placing them at the ends risks a tiny cut. Golden-section placement is the refinement that lets one probe be reused across steps.

Walking a foggy valley floor: one altitude reading tells you nothing about which way the bottom lies, because the same altitude appears on both slopes. Take two readings a stride apart and the comparison tells you which direction is downhill.

saying these in an interview costs you the question

  • Says ternary search cuts the interval to one third per step
  • Claims binary search works on any curve with a single minimum
  • Thinks a single probe's value reveals which side the minimum is on
  • Treats unimodality as something the algorithm verifies at runtime
  • Confuses finding an extremum's location with finding a target value
  • Assumes the function must be differentiable or continuous

context