Data Structures & AlgorithmsHardProduct Company SDE · binary search on answer
Problem: Koko eats bananas from piles [3, 6, 7, 11] and has h = 8 hours. She picks one pile per hour and eats up to k bananas from it. What is the minimum integer k that finishes in time? Run the binary search code.
Problem: Koko eats bananas from piles [3, 6, 7, 11] and has h = 8 hours. She picks one pile per hour and eats up to k bananas from it. What is the minimum integer k that finishes in time? Run the binary search code.
import math
piles = [3, 6, 7, 11]
h = 8
lo, hi = 1, max(piles)
while lo < hi:
mid = (lo + hi) // 2
hours = sum(math.ceil(p / mid) for p in piles)
if hours <= h:
hi = mid
else:
lo = mid + 1
print(lo)What is printed?- A. 3
- B. 4
- C. 5
- D. 6
Correct answer: B. 4
At k = 4 the hours are 1 + 2 + 2 + 3 = 8, while k = 3 needs 1 + 2 + 3 + 4 = 10 hours. Hours decrease monotonically in k, which is what makes binary search valid.
More Coding Interview Problems questions
- Problem: How many primes are there up to 100? Run the sieve. python n = 100 sieve = [True] (n + 1) sieve[0] = sieve[1] = False for i in…
- Problem: How many ways can the digit string '226' be decoded when 1 maps to A, 2 to B, ..., 26 to Z? Run the DP. python s = '226' dp = [1]…
- Problem: Union-find with path compression and union by rank performs m operations on n elements in what amortised time per operation?
- Problem: What is the largest rectangle area that can be formed in a histogram of heights [2, 1, 5, 6, 2, 3]? Use the stack code. python h…
- Problem: What is the minimum number of operations to sort the array [4, 3, 2, 1] using only swaps of adjacent elements? Run the code…
- Problem: Consider a graph where you must find the minimum 'maximum edge' on a path from s to t (a bottleneck path). Which algorithm…