Skip to main content

Search on the Answer

The answer is a number, not an index: a root, a speed, a capacity. Bisect the range of possible answers and test each guess.

The number line​

If a guess x works, every larger guess works too (or every smaller one). That turns the candidate values into a False ... False True ... True line, and the lower-bound loop finds the first True. The idea and the picture are on the hub page.

Picking lo and hi​

lo is the smallest answer that could possibly work, hi the largest you ever need: max(weights) and sum(weights) for shipping, 1 and max(piles) for Koko, 0 and x for a square root.

Writing canNot(mid)​

def canNot(mid): # True while mid is too small
... # a formula, or one O(n) greedy pass
lo, hi = smallest, largest
while lo < hi:
mid = lo + (hi - lo) // 2
if canNot(mid):
lo = mid + 1
else:
hi = mid
return lo

A formula costs O(1) per probe; a greedy pass costs O(n), so the whole search is O(n log(hi - lo)).

Min of max vs max of min​

"Minimize the largest piece" makes bigger guesses easier, so look for the first guess that works. "Maximize the smallest piece" makes bigger guesses harder: flip the test, or search for the last guess that works.

Invert a formula​

canNot is one line: x * x, x * (x + 1) / 2.

69. Sqrt(x)​

69. Sqrt(x)

LeetCode
Easy

Range Bisection

FIG. 69 SQRTX● INTERACTIVE
visualization loads as you reach it
class Solution:
def mySqrt(self, x: int) -> int:
# Answers [1, x+1]: lo can land on x+1, so step back with lo-1
# Upper bound: want the largest k with k*k <= x (last yes), lo stops on the first no, so the answer is lo-1
lo, hi = 1, x + 1
getSquare = lambda i: i * i
while lo < hi:
mid = lo + (hi - lo) // 2
if getSquare(mid) <= x:
lo = mid + 1
else:
hi = mid
return lo - 1
top ↑

367. Valid Perfect Square​

367. Valid Perfect Square

LeetCode
Easy

Range Bisection

FIG. 367 VALID PERFECT SQUARE● INTERACTIVE
visualization loads as you reach it
class Solution:
def isPerfectSquare(self, num: int) -> bool:
# Answers [1, num]: the root is never above num, so post-check lo * lo == num
# Lower bound: lo stops on the first k with k*k >= num, which is the root if one exists, so check lo in place
lo, hi = 1, num
getSqaure = lambda i: i * i
while lo < hi:
mid = lo + (hi - lo) // 2
if getSqaure(mid) < num:
lo = mid + 1
else:
hi = mid
return lo * lo == num
top ↑

441. Arranging Coins​

441. Arranging Coins

LeetCode
Easy

Range Bisection

FIG. 441 ARRANGING COINS● INTERACTIVE
visualization loads as you reach it
class Solution:
def arrangeCoins(self, n: int) -> int:
# Answers [1, n+1]: getNaturalSum(0) always fits, so lo moves past 0; lo lands one past the last full row, so return lo-1
# Upper bound: want the largest k with k*(k+1)//2 <= n (last yes), lo stops on the first no, so the answer is lo-1
lo, hi = 0, n + 1
getNaturalSum = lambda i: i * (i + 1) // 2
while lo < hi:
mid = lo + (hi - lo) // 2
if getNaturalSum(mid) <= n:
lo = mid + 1
else:
hi = mid
return lo - 1
top ↑

2485. Find the Pivot Integer​

2485. Find the Pivot Integer

LeetCode
Easy

Bisect on the Pivot

FIG. 2485 FIND THE PIVOT INTEGER BISECT● INTERACTIVE
visualization loads as you reach it
class Solution:
def pivotInteger(self, n: int) -> int:
naturalSum = lambda i: i * (i + 1) // 2
total = n * (n + 1) // 2
# Answers [0, n+1]: lo can land on n+1, so post-check that both sides balance at lo before returning it
lo, hi = 0, n + 1
while lo < hi:
mid = lo + (hi - lo) // 2
left = naturalSum(mid)
right = total - naturalSum(mid) + mid
if left < right:
lo = mid + 1
else:
hi = mid
return lo if naturalSum(lo) == total - naturalSum(lo) + lo else -1
top ↑

Minimize the max​

Greedy pass: fill a bucket until the guess overflows, then open the next one.

875. Koko Eating Bananas​

875. Koko Eating Bananas

LeetCode
Medium

Search on the Answer

FIG. 875 KOKO EATING BANANAS● INTERACTIVE
visualization loads as you reach it
class Solution:
def minEatingSpeed(self, piles: List[int], h: int) -> int:
def totalHours(mid):
hours = 0
for bananas in piles:
# hours += math.ceil(bananas/mid) # slower
hours += ((bananas - 1) // mid) + 1 # faster
return hours
 
# Answers [1, max(piles)]: eating max(piles) per hour always finishes in time
lo, hi = 1, max(piles)
while lo < hi:
mid = lo + (hi - lo) // 2
if totalHours(mid) > h:
lo = mid + 1
else:
hi = mid
return lo
top ↑

1011. Capacity To Ship Packages Within D Days​

1011. Capacity To Ship Packages Within D Days

LeetCode
Medium

Search on the Answer

FIG. 1011 CAPACITY TO SHIP PACKAGES WITHIN D DAYS● INTERACTIVE
visualization loads as you reach it
class Solution:
def shipWithinDays(self, weights: list[int], days: int) -> int:
def totalDays(capacity):
d = 1
current = 0
for w in weights:
if current + w > capacity:
d += 1
current = 0
current += w
return d
 
# Answers [max(weights), sum(weights)]: the total weight ships in one day, so hi is safe
lo, hi = max(weights), sum(weights)
while lo < hi:
mid = lo + (hi - lo) // 2
if totalDays(mid) > days:
lo = mid + 1
else:
hi = mid
return lo
top ↑

1283. Find the Smallest Divisor Given a Threshold​

1283. Find the Smallest Divisor Given a Threshold

LeetCode
Medium

Search on the Answer

FIG. 1283 FIND THE SMALLEST DIVISOR GIVEN A THRESHOLD● INTERACTIVE
visualization loads as you reach it
class Solution:
def smallestDivisor(self, nums: list[int], threshold: int) -> int:
def totalWith(divisor):
total = 0
for n in nums:
total += ((n - 1) // divisor) + 1
return total
 
# Answers [1, max(nums)]: divisor max(nums) makes every term 1, so the total is len(nums) <= threshold
lo, hi = 1, max(nums)
while lo < hi:
mid = lo + (hi - lo) // 2
if totalWith(mid) > threshold:
lo = mid + 1
else:
hi = mid
return lo
top ↑

1870. Minimum Speed to Arrive on Time​

1870. Minimum Speed to Arrive on Time

LeetCode
Medium

Search on the Answer

FIG. 1870 MINIMUM SPEED TO ARRIVE ON TIME● INTERACTIVE
visualization loads as you reach it
class Solution:
def minSpeedOnTime(self, dist: list[int], hour: float) -> int:
def totalHours(speed):
total = 0
for d in dist[:-1]:
total += ((d - 1) // speed) + 1
return total + dist[-1] / speed
 
# Answers [1, 10 ** 7]: LeetCode caps the answer at 10 ** 7, so post-check totalHours(lo) and return -1 if even that is late
lo, hi = 1, 10**7
while lo < hi:
mid = lo + (hi - lo) // 2
if totalHours(mid) > hour:
lo = mid + 1
else:
hi = mid
return lo if totalHours(lo) <= hour else -1
top ↑

410. Split Array Largest Sum​

410. Split Array Largest Sum

LeetCode
Hard

Search on the Answer

FIG. 410 SPLIT ARRAY LARGEST SUM● INTERACTIVE
visualization loads as you reach it
class Solution:
def splitArray(self, nums: List[int], m: int) -> int:
def canNotHold(mid):
total = 0
splits = 1
for num in nums:
if num > mid:
return False
total += num
if total > mid:
total = num
splits += 1
return splits > m
 
# Answers [max(nums), sum(nums)]: one piece holds everything, so hi is safe
lo, hi = max(nums), sum(nums)
while lo < hi:
mid = lo + (hi - lo) // 2
if canNotHold(mid):
lo = mid + 1
else:
hi = mid
return lo
top ↑

1482. Minimum Number of Days to Make m Bouquets​

1482. Minimum Number of Days to Make m Bouquets

LeetCode
Medium

Search on the Answer

FIG. 1482 MINIMUM NUMBER OF DAYS TO MAKE M BOUQUETS● INTERACTIVE
visualization loads as you reach it
class Solution:
def minDays(self, bloomDay: List[int], m: int, k: int) -> int:
def canNotBloom(mid): # Space optimized subproblem
flowers = 0
bouqets = 0
for bloom in bloomDay:
if flowers == k:
bouqets += 1
flowers = 0
if bloom > mid:
flowers = 0
else:
flowers += 1
bouqets += int(flowers == k)
return bouqets < m
 
if len(bloomDay) < m * k:
return -1
# Answers [1, max(bloomDay)]: past the -1 check, the last bloom day always works
lo, hi = 1, max(bloomDay)
while lo < hi:
mid = lo + (hi - lo) // 2
if canNotBloom(mid):
lo = mid + 1
else:
hi = mid
return lo
top ↑

2187. Minimum Time to Complete Trips​

2187. Minimum Time to Complete Trips

LeetCode
Medium

Search on the Answer

FIG. 2187 MINIMUM TIME TO COMPLETE TRIPS● INTERACTIVE
visualization loads as you reach it
class Solution:
def minimumTime(self, time: list[int], totalTrips: int) -> int:
def total(pivot_time):
total = 0
for t in time:
total += pivot_time // t
return total
 
# Answers [1, max(time) * totalTrips]: the slowest bus alone finishes every trip by hi
lo, hi = 1, max(time) * totalTrips
while lo < hi:
mid = lo + (hi - lo) // 2
if total(mid) < totalTrips:
lo = mid + 1
else:
hi = mid
return lo
top ↑

2594. Minimum Time to Repair Cars​

2594. Minimum Time to Repair Cars

LeetCode
Medium

Search on the Answer

FIG. 2594 MINIMUM TIME TO REPAIR CARS● INTERACTIVE
visualization loads as you reach it
class Solution:
def repairCars(self, ranks: list[int], cars: int) -> int:
def totalCars(minutes):
total = 0
for r in ranks:
total += math.isqrt(minutes // r)
return total
 
# Answers [0, 10**14]: worst case is rank 100 alone repairing 10**6 cars, 100 * (10**6)**2
lo, hi = 0, 10**14
while lo < hi:
mid = lo + (hi - lo) // 2
if totalCars(mid) < cars:
lo = mid + 1
else:
hi = mid
return lo
top ↑

1760. Minimum Limit of Balls in a Bag​

1760. Minimum Limit of Balls in a Bag

LeetCode
Medium

Search on the Answer

FIG. 1760 MINIMUM LIMIT OF BALLS IN A BAG● INTERACTIVE
visualization loads as you reach it
class Solution:
def minimumSize(self, nums: list[int], maxOperations: int) -> int:
def totalOps(balls):
total = 0
for n in nums:
total += math.ceil(n / balls) - 1
return total
 
# Answers [1, max(nums)]: a limit of max(nums) needs 0 splits, so it always works
lo, hi = 1, max(nums)
while lo < hi:
mid = lo + (hi - lo) // 2
if totalOps(mid) > maxOperations:
lo = mid + 1
else:
hi = mid
return lo
top ↑

2064. Minimized Maximum of Products Distributed to Any Store​

2064. Minimized Maximum of Products Distributed to Any Store

LeetCode
Medium

Search on the Answer

FIG. 2064 MINIMIZED MAXIMUM OF PRODUCTS DISTRIBUTED TO ANY STORE● INTERACTIVE
visualization loads as you reach it
class Solution:
def minimizedMaximum(self, n: int, quantities: list[int]) -> int:
def totalStores(store):
return sum(math.ceil(i / store) for i in quantities)
 
total = sum(quantities)
# Answers [1, max(quantities)]: at max(quantities) each type fits one store, so hi is safe
lo, hi = 1, max(quantities)
while lo < hi:
mid = lo + (hi - lo) // 2
if totalStores(mid) > n:
lo = mid + 1
else:
hi = mid
return lo
top ↑

Maximize the min​

The same pass with the direction flipped.

1231. Divide Chocolate​

1231. Divide Chocolate

LeetCode
Hard

Search on the Answer

FIG. 1231 DIVIDE CHOCOLATE● INTERACTIVE
visualization loads as you reach it
class Solution:
def maximizeSweetness(self, sweetness: List[int], k: int) -> int:
def canNotDivide(mid):
total_sweet = 0
splits = 0
for sweet in sweetness:
total_sweet += sweet
if total_sweet > mid:
total_sweet = 0
splits += 1
return (
splits > k
) # The reason is that when a fixed cutting plan with the minimal value x exists but we can not find a single piece with the sweetness of exactly x, it means that every piece has a sweetness greater than x.
 
# Answers [min(sweetness), sum(sweetness)]: with k = 0 nothing is cut, so hi is reachable
lo, hi = min(sweetness), sum(sweetness)
while lo < hi:
mid = lo + (hi - lo) // 2
if canNotDivide(mid):
lo = mid + 1
else:
hi = mid
return lo
top ↑

2226. Maximum Candies Allocated to K Children​

2226. Maximum Candies Allocated to K Children

LeetCode
Medium

Search on the Answer

FIG. 2226 MAXIMUM CANDIES ALLOCATED TO K CHILDREN● INTERACTIVE
visualization loads as you reach it
class Solution:
def maximumCandies(self, candies: list[int], k: int) -> int:
def totalChildren(candy):
total = 0
for c in candies:
total += c // candy
return total
 
# Answers [1, max(candies)+1]: lo lands one past the best size, so return lo - 1 (0 if size 1 fails)
lo, hi = 1, max(candies) + 1
while lo < hi:
mid = lo + (hi - lo) // 2
if totalChildren(mid) >= k:
lo = mid + 1
else:
hi = mid
return lo - 1
top ↑

1552. Magnetic Force Between Two Balls​

1552. Magnetic Force Between Two Balls

LeetCode
Medium

Search on the Answer

FIG. 1552 MAGNETIC FORCE BETWEEN TWO BALLS● INTERACTIVE
visualization loads as you reach it
class Solution:
def maxDistance(self, position: list[int], m: int) -> int:
def totalBalls(force):
total = 1
last = 0
for i in range(1, len(position)):
if position[i] - position[last] >= force:
total += 1
last = i
return total
 
position.sort()
# Answers [2, max(position) - min(position) + 1]: lo lands one past the best force, so return lo-1
lo, hi = 0, max(position) - min(position) + 1
while lo < hi:
mid = lo + (hi - lo) // 2
if totalBalls(mid) >= m:
lo = mid + 1
else:
hi = mid
return lo - 1
top ↑

2517. Maximum Tastiness of Candy Basket​

2517. Maximum Tastiness of Candy Basket

LeetCode
Medium

Search on the Answer

FIG. 2517 MAXIMUM TASTINESS OF CANDY BASKET● INTERACTIVE
visualization loads as you reach it
class Solution:
def maximumTastiness(self, price: list[int], k: int) -> int:
def totalCandies(tasty):
total = 1
last = 0
for i in range(1, len(price)):
if price[i] - price[last] >= tasty:
total += 1
last = i
return total
 
price.sort()
# Answers [1, 10**9]: lo lands one past the best tastiness, so return lo-1
lo, hi = 0, 10**9
while lo < hi:
mid = lo + (hi - lo) // 2
if totalCandies(mid) >= k:
lo = mid + 1
else:
hi = mid
return lo - 1
top ↑

2141. Maximum Running Time of N Computers​

2141. Maximum Running Time of N Computers

LeetCode
Hard

Search on the Answer

FIG. 2141 MAXIMUM RUNNING TIME OF N COMPUTERS● INTERACTIVE
visualization loads as you reach it
class Solution:
def maxRunTime(self, n: int, batteries: list[int]) -> int:
def totalComputers(minutes):
charge = sum(min(b, minutes) for b in batteries)
return charge // minutes
 
# Answers [1, sum(batteries)+1]: lo lands one past the best time, so return lo - 1
lo, hi = 1, sum(batteries) + 1
while lo < hi:
mid = lo + (hi - lo) // 2
if totalComputers(mid) >= n:
lo = mid + 1
else:
hi = mid
return lo - 1
top ↑

Kth smallest by counting​

canNot(mid) counts how many items are <= mid and compares the count with k.