Skip to contentKEEP THE CRAFTTHE SANCTUARY

Binary Search on Answer

Search possible answers only after proving that feasibility changes in one direction. Ordered shipment capacity separates an O(n) decision test from a first-feasible boundary search, so total cost includes every predicate call.

1 practice exercise3 interview problems

Recognize it when A proposed numeric answer can be checked without constructing every possible optimum.

Checking your account…

Binary Search on Answer Code Labs

Separate the Answer from an Input Position

The result here is a capacity, not the index of a weight. For a proposed capacity, scan positive weights in their original order, keeping one day’s load until the next item would exceed the capacity. Starting a new day at that point delays the split as far as possible, so the greedy scan uses the fewest days for that capacity.

Inspect Feasibility Before Searching It

Any individual weight larger than capacity makes that proposal impossible. Otherwise the table Lab counts days and compares used <= days. Increasing capacity can reuse every partition valid at a smaller capacity, so false results form a prefix and true results a suffix. Evaluating q explicit candidates costs O(nq). The candidates supplied to the table need not themselves be sorted, but sort your diagnostic proposals mentally when checking this transition.

Build a Capacity Feasibility Table

Reference
def capacity_table(weights,days,candidates):
    def feasible(capacity):
        used=1; load=0
        for weight in weights:
            if weight>capacity: return False
            if load+weight>capacity: used+=1; load=0
            load+=weight
        return used<=days
    return [feasible(value) for value in candidates]
Practice

Implement capacity_table(weights,days,candidates). Return whether each candidate capacity ships the ordered weights within days. weights is a nonempty list of positive integers; days is a positive integer. Preserve item order.

Public tests

  • Expose a monotone predicate

Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor

Build a Capacity Feasibility Table

def capacity_table(weights,days,candidates):
    def feasible(capacity):
        used=1; load=0
        for weight in weights:
            if weight>capacity: return False
            if load+weight>capacity: used+=1; load=0
            load+=weight
        return used<=days
    return [feasible(value) for value in candidates]

Keep a Known Feasible Answer in the Bounds

For nonempty positive weights, the minimum answer is at least max(weights), and sum(weights) is feasible in one day. The search therefore never needs to test an individually impossible capacity. When mid is feasible it could be the smallest answer, so keep it at right. When infeasible, all values through mid are impossible and left moves to mid+1.

Find Minimum Feasible Capacity

Reference
def minimum_capacity(weights,days):
    left,right=max(weights),sum(weights)
    def feasible(capacity):
        used=1; load=0
        for weight in weights:
            if load+weight>capacity: used+=1; load=0
            load+=weight
        return used<=days
    while left<right:
        mid=(left+right)//2
        if feasible(mid): right=mid
        else: left=mid+1
    return left
Practice

Implement minimum_capacity(weights,days). Return the smallest capacity that ships ordered weights within days. weights is a nonempty list of positive integers; days is a positive integer. Preserve item order.

Public tests

  • Keep the feasible boundary

Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor

Find Minimum Feasible Capacity

def minimum_capacity(weights,days):
    left,right=max(weights),sum(weights)
    def feasible(capacity):
        used=1; load=0
        for weight in weights:
            if load+weight>capacity: used+=1; load=0
            load+=weight
        return used<=days
    while left<right:
        mid=(left+right)//2
        if feasible(mid): right=mid
        else: left=mid+1
    return left

Keep Capacity 6 while Rejecting 5

The existing Lab on ordered weights [4, 2, 5] and days 2 should return 6. Each midpoint test packs the same order without rearranging items.

Step Executed statement State Why
Set proven bounds left,right=max(weights),sum(weights) left=5, right=11 Every item must fit, and all items fit at 11 in one day.
Test midpoint 8 mid=(left+right)//2 mid=8; loads are 6 then 5, used=2 The greedy predicate packs a maximal prefix on each day.
Keep feasible 8 if feasible(mid): right=mid left=5, right=8 8 succeeds but a smaller capacity may also succeed.
Keep midpoint 6 if feasible(mid): right=mid mid=6; used=2; left=5, right=6 6 is feasible, so the first-true convention retains this candidate.
Test midpoint 5 else: left=mid+1 mid=5; used=3; left=6, right=6 Capacity 5 needs too many days, so it and every smaller capacity are discarded.
Return minimum return left left=6 Convergence leaves the smallest feasible capacity.
Print Output
print(minimum_capacity([4, 2, 5], 2)) 6

Check the Boundary Convention before Reusing It

This first-true loop differs from finding the largest feasible value, where predicate direction and bound updates may reverse. Setting right=mid-1 here can discard the answer; setting left=mid can stop making progress when only two candidates remain. A nonpositive day budget or empty weights needs a separately defined contract, rather than this max(weights) initialization.

Explain Predicate Cost in an Interview

The answer interval shrinks logarithmically, but checking one capacity still scans n weights. Total time is O(n log(S+1)), with constant working state. A direct formula, greedy optimum or DP is preferable when it already constructs the answer in comparable time. Explain the known feasible upper bound, why feasibility is monotone, and how one branch retains the minimum candidate.

Template To Memorize

Learn this shape by heart; most problems in this family change only one or two lines of it.

Binary search on the answer

Guess an answer, check if it works, keep the smallest one that does.

You must find the smallest (or largest) value such that a check passes, and bigger values always pass once one does.

Trigger words

  • minimum speed
  • minimum capacity
  • within d days
  • within h hours
  • minimize the maximum
  • maximize the minimum
def min_eating_speed(piles, hours):
    def can_finish(speed):
        needed = 0
        for pile in piles:
            needed += (pile + speed - 1) // speed   # hours for this pile, rounded up
        return needed <= hours

    left, right = 1, max(piles)
    answer = right
    while left <= right:
        mid = (left + right) // 2
        if can_finish(mid):
            answer = mid          # works; try a smaller one
            right = mid - 1
        else:
            left = mid + 1
    return answer

Spot it when

  • 'Minimum speed / capacity / time so that ... within D days/hours'.
  • Checking one candidate is easy, but the candidate range is huge.

Remember

  • Only two things change between problems: the range of possible answers and the check function.
  • Total time is O(n log(range)).

How problems bend it

  • Ship packages within D days: Range is [max(weights), sum(weights)]; the check counts days needed at that capacity.
  • Largest value that still works: When the check passes, record mid and search right: left = mid + 1.

Python Version Note

Python 3.11+

Python // computes an integer midpoint without floating-point rounding; unbounded integer arithmetic is exact, while these interview bounds assume bounded-size numeric operations.

Verify in Python docs(opens in a new tab)

Complexity & Invariants

Interview bounds depend on the stated representation, input model, and real Python operations.

OperationAverageWorstInterview note
Minimum ordered shipping capacityO(n log(S + 1))O(n log(S + 1))n is number of weights and S their sum. Bounds max(weights) through S require O(n) setup; each predicate scans up to n weights.

Space

O(1) working state for the minimum-capacity Lab; the table returns O(q) feasibility flags.

Assumptions

  • Weights are a nonempty positive-integer list and days is positive. Increasing capacity preserves any earlier valid day partition, proving monotonicity.
  • Python // computes an integer midpoint without floating-point rounding; unbounded integer arithmetic is exact, while these interview bounds assume bounded-size numeric operations.

Invariants Worth Saying Aloud

  1. left through right contains the minimum feasible capacity, and right remains feasible.
  2. The shipping predicate processes weights in original order with each load at most capacity; the greedy day count is minimal for that capacity.

When To Use Or Avoid Binary Search on Answer

Use It When

  • Minimize ordered shipment capacity for positive weights and a positive day budget.
  • Search a numeric interval when a monotone feasibility proof and known feasible upper bound are available.

Choose Another Tool When

  • Use direct construction when it computes the optimum as simply or cheaply as repeated feasibility tests.
  • Do not binary-search a predicate with true-false-true behavior or bounds that exclude the answer.

Common Pitfalls

These are the mistakes most likely to survive a happy-path example and fail a boundary case.

Discarding a feasible midpoint

In a first-true interval [5, 6], feasible mid=5 is still an answer candidate; subtracting one moves right outside that candidate.

Prevent it: Keep mid itself when it is feasible under the first-true boundary convention.

Avoid

right = mid-1

Use instead

right = mid

Leaving an infeasible midpoint unresolved

With bounds [5, 6], integer midpoint 5 equals left. Assigning left=mid makes no progress after an infeasible test.

Prevent it: Discard the infeasible midpoint with left=mid+1.

Avoid

left = mid

Use instead

left = mid+1

Breaking an exactly full day early

A load 4 plus weight 2 fits capacity 6 exactly. Treating equality as overflow adds an unnecessary day and can reject a feasible capacity.

Prevent it: Start a new day only when load+weight > capacity; equality still fits.

Avoid

if load+weight >= capacity:
    used += 1
    load=0
load += weight

Use instead

if load+weight > capacity:
    used += 1
    load=0
load += weight

Reviewed References

Official Python documentation supports language behavior. Canonical problem pages provide additional practice context.