Guessing the right shoe size
Binary Search on the Answer
The analogy
You cannot compute the answer directly, but given any candidate you can check whether it works. So guess a size: too small? Guess bigger. Works? Try smaller and see if it still works. You are binary searching over possible answers rather than over an array.
Visualizer
Binary searching the answer
step 1 / 124
45
56
67
78
89
910
1011
1112
1213
1314
1415
1516
16Ship [3, 2, 2, 4, 1, 4] in 3 days. What is the smallest daily capacity that works? We cannot compute it directly — but given any capacity we can CHECK it.answer space: 4..16
def min_capacity(weights, days):
def check(cap): # monotone in cap
used, cur = 1, 0
for w in weights:
if cur + w > cap:
used, cur = used + 1, 0
cur += w
return used <= days
lo, hi = max(weights), sum(weights)
while lo < hi:
mid = (lo + hi) // 2
if check(mid):
hi = mid # feasible: try smaller
else:
lo = mid + 1 # infeasible: need bigger
return lo
# O(n log(sum)) — the check is the algorithm,
# the binary search is just the wrapperCheck yourself
What single property must check(x) have for this to be valid?