Seven interview problems that ask for the smallest or largest value that works. The move: write a check that says whether a value x is enough, then search the values, not the data.
You work on the back end of a moderation tool, a shipping service and a ride app. The seven problems on this street look unrelated. One asks how slowly a moderator can read, one asks how small a truck can be, and one asks how far apart lockers can stand.
Each of them asks for the smallest or the largest x that works. The data is not sorted, but the answers are ordered: if a capacity of 15 works, so does 16.
| Problem | The answer x | One pass checks that x is enough | Direction |
|---|---|---|---|
| Slowest rate that still finishes | a rate | the hours at this rate, rounded up, fit the limit | smallest |
| Smallest capacity that ships in d days | a capacity | a greedy load needs at most d days | smallest |
| Earliest day for m bouquets | a day | runs of k bloomed buds make m bouquets | smallest |
| Minimum time for all trips | minutes | the whole trips of all drivers reach the total | smallest |
| Minimise the widest pair gap | a gap | pairing close neighbours gives enough pairs | smallest |
| Kth smallest gap between two builds | a gap | at least k pairs are at most x apart | smallest |
| Largest minimum gap between lockers | a gap | enough lockers fit with every gap at least x | largest |
Read the last two columns. A check that costs one pass, and a direction that is clear, are what let you search the answers instead of the data.
Exercise · Predict the output: Which rates does the search try?. The queues hold 30, 11, 23, 4 and 20 posts, and all must finish in 6 hours. The code tries rates and records each one. What does it print?
queues = [30, 11, 23, 4, 20]
hours = 6
lo, hi = 1, 30
out = ""
while lo < hi:
mid = (lo + hi) // 2
out += str(mid) + ","
if sum((q + mid - 1) // mid for q in queues) <= hours:
hi = mid
else:
lo = mid + 1
print(out + str(lo))The move has two parts, and you make them before you write any code.
First, write can(x): a check that reads the data once and says whether x is enough. Say what bigger x does. For a rate, a capacity or a day, a bigger x can only help, so can is false and then true.
Second, find the smallest x with can(x) true, between the lowest and the highest value that x can take. This is the first-true loop from the Academy, run over answers instead of positions.
For the queues above, the table shows the hours needed at some rates.
| Rate | Hours needed | Within 6 hours? |
|---|---|---|
| 15 | 8 | no |
| 22 | 7 | no |
| 23 | 6 | yes |
| 24 | 6 | yes |
| 30 | 5 | yes |
At every step, can(x) is false for every x below lo and true for every x from hi on. When lo meets hi, the answer is lo.
The loop costs one pass of the data for each step. For 100,000 parcels with a range of 100,000,000,000 capacities, that is 37 passes, or 3,700,000 steps, not one pass per capacity.
Check a rate with one pass: at 22 the queues need 7 hours, at 23 they need 6, so 23 is the first rate that fits.
Exercise · Find the bug: The lowest capacity. This returns the smallest capacity that ships all the parcels in at most the given number of days. A parcel cannot be split, and the parcels go in order. It is wrong for some inputs. Which line is wrong?
def ship_capacity(weights, days):
heaviest, total = max(weights), sum(weights)
lo, hi = 1, total
while lo < hi:
mid = (lo + hi) // 2
if days_needed(weights, mid) <= days:
hi = mid
else:
lo = mid + 1
return lo
def days_needed(weights, capacity):
needed, load = 1, 0
for w in weights:
if load + w > capacity:
needed += 1
load = 0
load += w
return neededThe Academy lesson Search on the answer teaches the loop with a rate and a capacity. The first-true template teaches the loop itself. This street does not teach them again. It changes four things.
The bounds are part of the problem. The lowest capacity is the heaviest parcel, as the bug above shows. The highest is the total weight, and for 100,000 parcels of weight 1,000,000 that is 100,000,000,000, which needs 64 bits.
The trip problem reaches higher: with 1,000,000 minutes for one trip and 1,000,000,000 trips, the answer can be 1,000,000,000,000,000 minutes.
The check is a different tool each time. A greedy pass fits the capacity and the lockers. A sum of whole divisions fits the trips. The kth gap has no list to index, so count the pairs at most x apart with two pointers.
For 100,000 builds there are 4,999,950,000 pairs, so the count is a 64-bit number.
Some problems ask for the largest x. For the lockers, can(x) is true for small gaps and false for large ones. The loop keeps lo = mid on success, so the middle must round up.
A check can be true for every x, or for none. A bouquet day may not exist, so the highest day must still be tested, and the problem asks for -1.
Exercise · Put it in order: The largest minimum gap. Arrange the lines into a search that returns the largest gap g for which the lockers fit with every two at least g apart. The spots are sorted, and the check can_place is given.
def max_min_gap(spots, lockers):
lo = 1
hi = spots[-1] - spots[0]
while lo < hi:
mid = lo + (hi - lo + 1) // 2
if can_place(spots, lockers, mid):
lo = mid
else:
hi = mid - 1
return lo
mid = lo + (hi - lo) // 2Start the capacity search at the heaviest parcel. From 1, a capacity too small for a parcel can pass the greedy check.
Solve them in this order. The first four use a simple check over the whole data, and the last three need a smarter check or the largest answer.
Before you code each problem, write two lines: what can(x) reads and returns, and the lowest and the highest value of x. If you cannot say what a bigger x does to the check, the answers are not ordered yet.
Give each problem about 25 minutes. Spend the first five on the two lines, and write can(x) as its own function before you write the search.
Test can(x) by hand on three values: one that is too small, one that is exactly right, and one that is too big. It must read false, true, true.
Four edge cases come back on almost every rung. The lowest bound is wrong, the highest bound is not enough, the answer is the largest x, and a sum needs 64 bits. Write one small test for each.
Checkpoint · Search on the answer
Q1/5 What does the search run over in these problems?
Answer: B
The data is not sorted, but the answers are ordered: if x works, a larger x works too. The search looks at values of x.
Q2/5 What must hold for the first-true loop to work on can(x)?
Answer: B
The loop needs a check that turns from false to true once. Without that order, ruling out half of the values is not safe.
Q3/5 The parcels weigh 1, 1 and 5, and they must ship in 2 days. Why must the lowest capacity be 5, not 1?
Answer: B
With a capacity of 2 the greedy pass counts the weight 5 as a day of its own, and wrongly passes. The lowest bound must be the heaviest parcel.
Q4/5 Why can the highest time in the trips problem need more than 32 bits?
Answer: B
The slowest driver alone needs trip time multiplied by the number of trips. That product is far above 2,147,483,647.
Q5/5 You search for the largest gap and keep lo = mid when the check passes. What must the middle do?
Answer: B
With lo = 3 and hi = 4, a middle that rounds down is 3 again, so lo = mid changes nothing and the search never ends.
Review cards from this lesson.
A few questions, then explain the idea back in your own words. Your tutor marks it. Quiz and explain back.