Search the Answer
What is this?
A shop assistant is finding your shoe size without a measuring device. She does not inspect your foot and compute an answer — she hands you a size, asks "too tight?", and halves the range. Nothing is being searched in the usual sense; the candidate answers are the search space, and a yes/no test navigates them.
That is this chapter. You are given no sorted array at all. You invent one out of the possible answers.
💡 Fun fact: Maximum Value at a Given Index in a Bounded Array is a binary search whose predicate is closed-form arithmetic rather than a loop. Once the peak value is fixed, the cheapest possible array descends by one on each side and then flattens out at 1 — so the minimum total is two arithmetic series plus a flat remainder, computable in O(1). The whole problem becomes
O(log(max))with no iteration at all, which is why getting the series formula right matters more than the search.
🔓 The 2 problems in this chapter are free. Sign in with Google or Microsoft to start solving.
The one-line idea: if the problem says "smallest / largest / minimum possible x such that…", then
xis your search space. Writefeasible(x), prove it flips exactly once, and binary-search the flip.
1. The three steps
Step 1 — bound the space. Pick lo and hi that certainly bracket the answer. Sloppy bounds are the commonest source of wrong answers: lo must be a value that might be feasible, and hi one that certainly is. For Heaters, lo = 0 and hi = the largest possible coordinate distance.
Step 2 — write the predicate. feasible(x) answers "can the goal be met with this value?" It is usually a greedy sweep in O(n), occasionally a formula in O(1).
Step 3 — prove monotonicity. If a radius of 5 covers every house, so does 6. If a ship of capacity 20 delivers in time, so does 21. State the argument out loud — this is the part that makes the whole approach valid, and it is the part candidates skip.
lo, hi = 0, max_possible
while lo < hi:
mid = lo + (hi - lo) // 2
if feasible(mid):
hi = mid # mid works — it might be the smallest that does
else:
lo = mid + 1 # mid fails — the answer is strictly larger
return lo
2. When the predicate is a formula
For the bounded-array problem, fix the peak value v at index i. The cheapest array with that peak descends v−1, v−2, … outward until it hits 1, then stays flat. Each side is therefore an arithmetic series plus a flat tail:
Add both sides plus v itself and compare with the budget. No loop, no simulation — and the feasibility check is O(1), which is what makes the whole solution O(log(max)).
3. A 30-second worked example (Heaters)
Houses at [1, 2, 3, 4], heaters at [1, 4]. What is the smallest radius covering every house?
Feasibility is monotonic in the obvious way: if radius r covers every house, r + 1 covers a superset of the same area. That one sentence is the justification the whole solution rests on.
4. Where you'll actually meet this
- Capacity and autoscaling. "What is the smallest cluster size that keeps p99 latency under target?" — feasibility measured by a load test, monotonic by assumption.
- Rate limiting. The largest request rate that keeps error rates acceptable.
- Facility placement. Heaters is a real coverage problem — cell towers, warehouses, charging stations — asking for the minimum service radius.
- Build and deploy tooling.
git bisectbinary-searches commits on the monotone predicate "is the bug present?". - Numerical root-finding. Bisection over a continuous range, with the same monotonicity requirement.
5. Problems in this chapter
▶ Maximum Value at a Given Index in a Bounded Array
Maximise the value at a given index subject to a sum limit and adjacent values differing by at most one. Binary-search the peak; feasibility is two arithmetic series in O(1).
Pattern: search the answer, closed-form predicate. Target: O(log(maxSum)) time, O(1) space.
▶ Heaters
Find the minimum heater radius covering all houses. Binary-search the radius with a greedy coverage check — or sort both arrays and take the maximum nearest-heater distance directly.
Pattern: search the answer, greedy predicate. Target: O((n + m) log(range)), or O(n log n) via the direct method.
6. Common pitfalls 🚫
- Not proving monotonicity. If
feasiblecan flip more than once, binary search returns an arbitrary point. This is the step that matters. - Bad bounds.
himust certainly be feasible andlomust be a legal candidate; otherwise the loop converges on a value that was never valid. - Mixing loop conventions.
while lo < hipairs withhi = midandlo = mid + 1. Combining it withhi = mid - 1loops forever or skips the answer. - Overflow in
(lo + hi) / 2. Uselo + (hi - lo) // 2— a habit worth keeping even in Python, since interviews are polyglot. - Off-by-one in the arithmetic series. The peak itself must be counted once, not once per side.
- Forgetting the flat tail. When the descent reaches 1 before the array ends, the remaining cells each contribute 1, not 0.
- Missing the simpler solution. Heaters has a direct sorted-two-pointer answer; binary search is instructive but not the only route, and saying so is a plus.
7. Key takeaways
- "Smallest/largest x such that…" means x is the search space. Recognising that phrasing is most of the battle.
- Feasibility is the design work, and it is usually a greedy sweep or a formula.
- Monotonicity is the licence. Prove it in one sentence before writing the loop.
- Bound the space carefully. Bad bounds produce plausible, wrong answers.
- One loop template, always.
while lo < hi,hi = mid,lo = mid + 1, returnlo. - An O(1) predicate makes the whole thing logarithmic — look for closed forms before reaching for simulation.
- Why interviewers love it: the problem statement contains no array and no mention of searching, so recognising the pattern at all is the signal.
Order: Maximum Value at a Given Index in a Bounded Array → Heaters.
The two problems that introduce this pattern — Capacity To Ship Packages Within D Days and Kth Missing Positive Number — are in Coding Interview 101. Do those first; the two here assume you can already spot the monotonic predicate unaided.
Maximum Value at a Given Index in a Bounded Array
Core idea: The answer — the largest possible
arr[index]— is a single
number, and feasibility is monotone: if a peak ofvfits under the budget,
so does any smaller peak. So binary-search the peak value itself. For a
candidate peakv, the cheapest legal array slopes down by 1 on each side ofindex(clamped at 1), and that minimum sum has a closed-form arithmetic
formula. Keep the largestvwhose minimum sum is≤ maxSum.
Problem, rephrased
A city planner is laying out building heights along a street of n plots, and the mayor wants the tallest possible landmark tower on one particular plot. You're given three integers: n, the number of plots; index, the plot that gets the landmark; and maxSum, the total number of floors the concrete budget can pay for. The heights form an array arr of length n in which every value is a positive integer — each plot must hold at least a 1-floor building — and adjacent values differ by at most 1 (|arr[i] - arr[i+1]| <= 1), because zoning demands a smooth skyline with no cliffs between neighbours.
Return the maximum possible value of arr[index] over all height arrays that satisfy both rules and keep the total within budget: sum(arr) <= maxSum. Note that n and maxSum each reach about 10^9, so any approach that builds the street plot-by-plot is already too slow.
Strip the story away and this is the classic Maximum Value at a Given Index in a Bounded Array: construct a length-n array of positive integers with |arr[i] - arr[i+1]| <= 1 and sum(arr) <= maxSum that maximizes arr[index], and return that maximum.
n |
index |
maxSum |
Output | Why |
|---|---|---|---|---|
4 |
2 |
6 |
2 |
[1,1,2,1] sums to 5; pushing the peak to 3 needs [1,2,3,2]=8 > 6. |
6 |
1 |
10 |
3 |
[1,3,2,1,1,1]-style descent fits in 10; 4 would overflow. |
1 |
0 |
5 |
5 |
One plot, no neighbours — spend the whole budget on it. |
Sign in to continue reading
The rest of this lesson is available with a free account. Signing in with Google or Microsoft is free.
Sign in to read the full lesson