Binary search over possible answers with a feasibility check.
Use it when the answer is a number, and you can test one candidate easily. A bigger candidate must never hurt, or a smaller one must never hurt. Signal words: the smallest speed that still works, minimise the largest, maximise the smallest.
Start lo is the smallest candidate that could be the answer. hi is a candidate that is certain to pass the check. The window [lo, hi) holds the candidates still in question.
Step while lo < hi, set mid = lo + (hi - lo) / 2 and run the check on mid. If it passes, set hi = mid. Otherwise set lo = mid + 1.
Stop when lo == hi. The answer is lo. For a largest answer, search for the first candidate that fails, and return lo - 1.
It does not work when the check can pass, then fail, then pass again.
Cost: at most floor(log2 of the number of candidates) + 1 checks, and each check costs one pass over the input: O(n log range). Extra space is O(1).
In this lesson you use the first-true template on a list that does not exist. The candidates are the possible answers, such as speeds, capacities and lengths. You write a check that tests one candidate, prove that the check flips only once, and search the range of answers with it.
You work on the log archiver of a monitoring system. Every night it uploads a queue of files to cold storage. The uploader sends r blocks an hour, and it handles one file at a time. It starts the next file only at the top of the hour, so a file of s blocks takes s / r hours, rounded up to a whole hour.
Your team lead says: The night window is
Hhours. A faster uploader costs more in network fees, so give me the slowest whole rate that still uploads every file in time.
Here is a short test: files of 40, 12, 27, 5 and 18 blocks, and a window of 9 hours. A real queue holds up to 100,000 files, and a disk image can reach 10^7 blocks.
So the task is this: find the slowest rate that finishes in time, without trying every rate.
A friend thinks of a number from 1 to 100, and you may ask about one number at a time. After each guess your friend says "higher" or "lower".
You never see a list of numbers. You guess 50, and the answer tells you which half holds the secret number. After about 7 guesses you know it.
Here the friend is a check. You try one rate, and the check says "too slow" or "fast enough". That tells you which side of the rate holds the answer.
Like guessing a secret number from higher and lower: there is no list, and each answer rules out half, as a check does for answers.
Before you write code, solve the test by hand. It shows what one question costs.
Solve it by hand: Five files and 9 hours: find the slowest rate that finishes. The hand-solve sheet loads in your browser.
You try the rates from 1 upwards. For each rate you add up the hours that the five files need, rounded up.
Files: [40, 12, 27, 5, 18], and the window is 9 hours.
| Rate | Hours for each file | Total hours | At most 9? |
|---|---|---|---|
| 1 | 40, 12, 27, 5, 18 | 102 | no |
| 2 | 20, 6, 14, 3, 9 | 52 | no |
| 5 | 8, 3, 6, 1, 4 | 22 | no |
| 9 | 5, 2, 3, 1, 2 | 13 | no |
| 10 | 4, 2, 3, 1, 2 | 12 | no |
| 12 | 4, 1, 3, 1, 2 | 11 | no |
| 13 | 4, 1, 3, 1, 2 | 11 | no |
| 14 | 3, 1, 2, 1, 2 | 9 | yes |
The rows for the rates 3, 4, 6, 7, 8 and 11 are left out, and they also say no. You made 14 tries, and each try read all 5 files. The slowest rate that works is 14.
Start with a correct version. Try each rate from 1, and stop at the first rate that fits.
def slowest_rate_scan(sizes, hours):
rate = 1
while True:
needed = 0
for s in sizes: # one pass over the queue
needed += (s + rate - 1) // rate # rounded up
if needed <= hours:
return rate
rate += 1This is correct. One try reads the whole queue, and the number of tries is the answer itself: up to the largest file.
Now check the real size.
The queue holds 100,000 files, and the largest file is 10^7 blocks.
Here is the count:
So the planner would run for hours to answer one question, and the team asks it every night.
Predict the cost
Q The queue holds 100,000 files, and the answer can be as large as 10^7. Each try reads every file, and the first attempt tries every rate from 1. About how many steps is that, in the worst case?
Answer: C
The count is 10^7 tries × 10^5 files = 10^12. At about 10^8 steps a second, that is about 10^4 seconds.
The first attempt is correct, but it never uses what the table showed. Now the team does.
Look at the hand trace again. The total hours only went down when the rate went up: 102, 52, 22, 13, 12, 11, 9. The answers to "at most 9 hours?" read no for the rates 1 to 13, and yes for 14.
That is false and then true for ever, the shape from the first lesson. The list here is not an array of input. It is the line of possible rates, 1, 2, 3 and so on, and the condition is the check "at most 9 hours".
Why does the check flip only once? Take a file of s blocks and two rates, r and a faster r2. At the faster rate the file takes s / r2 hours, which is at most s / r, so after rounding up it still takes at most as many hours. Every file takes at most as many hours, so the total can only go down.
This is the idea of a feasibility check. It is a test on one candidate answer that says whether the candidate works. When it is monotone, a candidate that works means that every faster rate works too. So you can run the first-true template on the rates, without building any list.
The hours needed only go down as the rate goes up, so the check at most 9 hours flips once and a binary search over rates works.
Two numbers start the search. The lowest rate that could work is 1, because a rate is a whole number of blocks an hour. A rate that certainly works is the largest file, 40: every file then takes exactly 1 hour, so the total is 5 hours, which fits the 9-hour window. A faster rate cannot do better, so the answer is between 1 and 40.
Race: Try every rate, against the window search. The operation counter loads in your browser.
The race counts the worst case. If the largest file has 100,000 blocks, the first attempt tries up to 100,000 rates, and the window search makes 17 checks. At 10^7 blocks the search makes at most 24 checks, and each check reads 100,000 files, so it is about 2.4 million steps and not 10^12.
The files are [36, 14, 25, 6, 19] and the window is 10 hours. The player runs the search over the rates 1 to 36. It stops at six steps and asks you to predict.
Dry run: Predict each step: five files and 10 hours. The step-by-step player loads in your browser.
Reading without the player? Cover the last columns and predict them row by row.
| Step | lo | hi | mid | Hours needed at mid | What moves |
|---|---|---|---|---|---|
| 1 | 1 | 36 | 18 | 8 | 8 is at most 10, so hi moves to 18 |
| 2 | 1 | 18 | 9 | 13 | 13 is more than 10, so lo moves to 10 |
| 3 | 10 | 18 | 14 | 9 | 9 is at most 10, so hi moves to 14 |
| 4 | 10 | 14 | 12 | 11 | 11 is more than 10, so lo moves to 13 |
| 5 | 13 | 14 | 13 | 10 | 10 is at most 10, so hi moves to 13 |
| end | 13 | 13 | none | the window is empty, so the answer is 13 |
Look at step 5. The rate 13 needs exactly 10 hours, which fits, and it is the slowest such rate, because 12 needs 11.
The end of the search is where off-by-one mistakes hide, so look at the last two steps of the table above.
At step 4 the window is [10, 14), which holds the rates 10 to 13. The middle is 12, which needs 11 hours. That is too slow, so it and every slower rate are ruled out, and lo moves to 13.
At step 5 the window is [13, 14). It holds one rate, so the middle is 13 itself. It needs 10 hours, which fits, so it may be the slowest, and hi moves to 13.
Now lo == hi == 13, the window is empty, and the slowest rate is 13. The rate 14, which was the earlier hi, was never the answer, because 13 also fits.
Here is the rule that keeps a search on the answer correct. Every line of the template exists to protect it.
Every candidate before lo fails the check, and every candidate from hi on passes it, so lo ends as the smallest candidate that passes.
At the start, lo is the smallest candidate that could be an answer, so no candidate is before it. And hi is a candidate that is known to pass, so every candidate from hi on passes, because the check is monotone. The rule holds.
If the check fails at mid, every candidate up to mid fails too, so lo = mid + 1 keeps the rule. If it passes, every candidate from mid on passes too, so hi = mid keeps the rule. The loop ends for the same reason as before: the window at least halves at every step. When lo == hi, lo is the smallest candidate that passes.
Because hi is known to pass, the search never needs to test it. That is why the window [lo, hi) is enough: the answer is in [lo, hi], and hi itself is only returned when nothing before it passes.
Use it when the answer is a number, and you can test one candidate easily. A bigger candidate must never hurt, or a smaller one must never hurt. Signal words: the smallest speed that still works, minimise the largest, maximise the smallest.
Start: lo is the smallest candidate that could be the answer. hi is a candidate that is certain to pass the check. The window [lo, hi) holds the candidates still in question.
Step: while lo < hi, set mid = lo + (hi - lo) / 2 and run the check on mid. If it passes, set hi = mid. Otherwise set lo = mid + 1.
Stop: when lo == hi. The answer is lo. For a largest answer, search for the first candidate that fails, and return lo - 1.
It does not work when the check can pass, then fail, then pass again.
Cost: at most floor(log2 of the number of candidates) + 1 checks, and each check costs one pass over the input: O(n log range). Extra space is O(1).
def slowest_rate(sizes, hours):
# [1] The candidates are the whole rates 1 to the largest file. At that rate every file takes one hour, so it works when there are enough hours: hi starts there.
lo = 1
hi = max(sizes)
# [2] While the window holds a rate, look at the rate in its middle.
while lo < hi:
mid = lo + (hi - lo) // 2
# [3] The check for this one rate: add up the whole hours each file needs, rounding up.
needed = 0
for s in sizes:
needed += (s + mid - 1) // mid
if needed <= hours:
# [4] The rate is fast enough, so every faster rate is too. It may be the slowest, so keep it: hi moves to it.
hi = mid
else:
# [5] The rate is too slow, so every slower rate is too. lo moves past it.
lo = mid + 1
# [6] The window is empty: lo is the slowest rate that finishes in time.
return lopublic int slowestRate(int[] sizes, long hours) {
// [1] The candidates are the whole rates 1 to the largest file. At that rate every file takes one hour, so it works when there are enough hours: hi starts there.
int lo = 1;
int hi = 0;
for (int s : sizes) {
hi = Math.max(hi, s);
}
// [2] While the window holds a rate, look at the rate in its middle.
while (lo < hi) {
int mid = lo + (hi - lo) / 2;
// [3] The check for this one rate: add up the whole hours each file needs, rounding up.
long needed = 0;
for (int s : sizes) {
needed += ((long) s + mid - 1) / mid;
}
if (needed <= hours) {
// [4] The rate is fast enough, so every faster rate is too. It may be the slowest, so keep it: hi moves to it.
hi = mid;
} else {
// [5] The rate is too slow, so every slower rate is too. lo moves past it.
lo = mid + 1;
}
}
// [6] The window is empty: lo is the slowest rate that finishes in time.
return lo;
}int slowestRate(vector<int>& sizes, long long hours) {
// [1] The candidates are the whole rates 1 to the largest file. At that rate every file takes one hour, so it works when there are enough hours: hi starts there.
int lo = 1;
int hi = 0;
for (int s : sizes) {
hi = max(hi, s);
}
// [2] While the window holds a rate, look at the rate in its middle.
while (lo < hi) {
int mid = lo + (hi - lo) / 2;
// [3] The check for this one rate: add up the whole hours each file needs, rounding up.
long long needed = 0;
for (int s : sizes) {
needed += ((long long)s + mid - 1) / mid;
}
if (needed <= hours) {
// [4] The rate is fast enough, so every faster rate is too. It may be the slowest, so keep it: hi moves to it.
hi = mid;
} else {
// [5] The rate is too slow, so every slower rate is too. lo moves past it.
lo = mid + 1;
}
}
// [6] The window is empty: lo is the slowest rate that finishes in time.
return lo;
}function slowestRate(sizes, hours) {
// [1] The candidates are the whole rates 1 to the largest file. At that rate every file takes one hour, so it works when there are enough hours: hi starts there.
let lo = 1;
let hi = 0;
for (const s of sizes) {
hi = Math.max(hi, s);
}
// [2] While the window holds a rate, look at the rate in its middle.
while (lo < hi) {
const mid = lo + Math.floor((hi - lo) / 2);
// [3] The check for this one rate: add up the whole hours each file needs, rounding up.
let needed = 0;
for (const s of sizes) {
needed += Math.ceil(s / mid);
}
if (needed <= hours) {
// [4] The rate is fast enough, so every faster rate is too. It may be the slowest, so keep it: hi moves to it.
hi = mid;
} else {
// [5] The rate is too slow, so every slower rate is too. lo moves past it.
lo = mid + 1;
}
}
// [6] The window is empty: lo is the slowest rate that finishes in time.
return lo;
}Rebuild the template: put its lines back in order. Loads in your browser.
The two bounds are part of the answer, and a wrong bound gives a wrong result. For every problem, write down three things: the check, why it is monotone, and why the range is enough.
| Problem | The check on a candidate | Why it flips once | lo and hi |
|---|---|---|---|
| Slowest upload rate | The files need at most H hours at this rate |
A faster rate never needs more hours: s / r rounded up can only go down |
lo = 1, because rates are whole and positive. hi = the largest file, where every file takes 1 hour, so the total is the number of files, which fits when there are at least as many hours as files |
Smallest heaviest load when a list of loads is split into k runs |
The loads can be cut into at most k runs, each with a sum of at most L |
A cut that works for L works for every larger L |
lo = the largest single load, because some run holds it. hi = the sum of all loads, where one run is enough |
Longest piece length with at least k pieces |
The ribbons give at least k pieces of this length |
A shorter piece never gives fewer pieces: r / L rounded down can only go up as L goes down |
lo = 1. hi = the longest ribbon plus 1, which gives no piece, so it fails |
The range is enough because the answer cannot lie outside it. Below lo no candidate can work, and at hi a candidate certainly works, so nothing larger needs a look.
A delivery app has a day's orders in the order they arrive, with loads [4, 9, 3, 7, 2, 8]. The orders must go to 3 couriers, and each courier takes a run of neighbouring orders. What is the smallest possible heaviest load?
The check on a load L starts a new run when the next order does not fit. It counts the runs, and L works when there are at most 3. For L = 13 the runs are [4, 9], [3, 7, 2] and [8], with loads 13, 12 and 8, so 3 runs. For L = 12 the runs are [4], [9, 3], [7, 2] and [8], so 4 runs: too many.
Why does the greedy check give the fewest runs? It makes every run as long as it can. By induction, each of its runs reaches at least as far as the matching run of any valid cut. So if any cut with at most 3 runs exists, the greedy one has at most 3 runs.
The range is lo = 9, the heaviest order, because some courier takes it, and hi = 33, the sum, where one courier takes everything.
| Step | lo | hi | mid | Runs at mid | What moves |
|---|---|---|---|---|---|
| 1 | 9 | 33 | 21 | 2 | 2 is at most 3, so hi moves to 21 |
| 2 | 9 | 21 | 15 | 3 | hi moves to 15 |
| 3 | 9 | 15 | 12 | 4 | too many, so lo moves to 13 |
| 4 | 13 | 15 | 14 | 3 | hi moves to 14 |
| 5 | 13 | 14 | 13 | 3 | hi moves to 13 |
| end | 13 | 13 | the heaviest load is 13 |
Only the check changed. The same search gives the capacity of a truck that ships parcels in order within d days, with days in place of couriers.
Exercise · Put it in order: The check for a load limit. Arrange the lines into the check from the delivery problem: the number of runs needed when each run may carry at most limit and the loads stay in order.
def runs_needed(loads, limit):
runs = 1
current = 0
for x in loads:
if current + x > limit:
runs += 1
current = 0
current += x
return runs
if current + x >= limit:To split orders between k couriers, the check starts a new run when the next order does not fit, and the search finds the smallest heaviest load.
Sometimes you want the largest candidate. The check then passes for small candidates and fails for large ones. You search for the first candidate that fails, and the answer is the one before it.
def longest_piece(ribbons, k):
# [1] The candidates are the whole lengths 1 to the longest ribbon. One more than that gives no piece at all, so it fails when k is at least 1: hi starts there.
lo = 1
hi = max(ribbons) + 1
# [2] While the window holds a length, look at the length in its middle.
while lo < hi:
mid = lo + (hi - lo) // 2
# [3] The check for this one length: count the whole pieces that every ribbon gives.
pieces = 0
for r in ribbons:
pieces += r // mid
if pieces >= k:
# [4] Enough pieces, so every shorter length gives enough too. lo moves past mid.
lo = mid + 1
else:
# [5] Too few pieces, so every longer length gives too few. mid may be the first length that fails, so keep it: hi moves to it.
hi = mid
# [6] The window is empty: lo is the first length that fails, so lo - 1 is the longest length that works. It is 0 when none works.
return lo - 1public int longestPiece(int[] ribbons, long k) {
// [1] The candidates are the whole lengths 1 to the longest ribbon. One more than that gives no piece at all, so it fails when k is at least 1: hi starts there.
int lo = 1;
int hi = 0;
for (int r : ribbons) {
hi = Math.max(hi, r);
}
hi = hi + 1;
// [2] While the window holds a length, look at the length in its middle.
while (lo < hi) {
int mid = lo + (hi - lo) / 2;
// [3] The check for this one length: count the whole pieces that every ribbon gives.
long pieces = 0;
for (int r : ribbons) {
pieces += r / mid;
}
if (pieces >= k) {
// [4] Enough pieces, so every shorter length gives enough too. lo moves past mid.
lo = mid + 1;
} else {
// [5] Too few pieces, so every longer length gives too few. mid may be the first length that fails, so keep it: hi moves to it.
hi = mid;
}
}
// [6] The window is empty: lo is the first length that fails, so lo - 1 is the longest length that works. It is 0 when none works.
return lo - 1;
}int longestPiece(vector<int>& ribbons, long long k) {
// [1] The candidates are the whole lengths 1 to the longest ribbon. One more than that gives no piece at all, so it fails when k is at least 1: hi starts there.
int lo = 1;
int hi = 0;
for (int r : ribbons) {
hi = max(hi, r);
}
hi = hi + 1;
// [2] While the window holds a length, look at the length in its middle.
while (lo < hi) {
int mid = lo + (hi - lo) / 2;
// [3] The check for this one length: count the whole pieces that every ribbon gives.
long long pieces = 0;
for (int r : ribbons) {
pieces += r / mid;
}
if (pieces >= k) {
// [4] Enough pieces, so every shorter length gives enough too. lo moves past mid.
lo = mid + 1;
} else {
// [5] Too few pieces, so every longer length gives too few. mid may be the first length that fails, so keep it: hi moves to it.
hi = mid;
}
}
// [6] The window is empty: lo is the first length that fails, so lo - 1 is the longest length that works. It is 0 when none works.
return lo - 1;
}function longestPiece(ribbons, k) {
// [1] The candidates are the whole lengths 1 to the longest ribbon. One more than that gives no piece at all, so it fails when k is at least 1: hi starts there.
let lo = 1;
let hi = 0;
for (const r of ribbons) {
hi = Math.max(hi, r);
}
hi = hi + 1;
// [2] While the window holds a length, look at the length in its middle.
while (lo < hi) {
const mid = lo + Math.floor((hi - lo) / 2);
// [3] The check for this one length: count the whole pieces that every ribbon gives.
let pieces = 0;
for (const r of ribbons) {
pieces += Math.floor(r / mid);
}
if (pieces >= k) {
// [4] Enough pieces, so every shorter length gives enough too. lo moves past mid.
lo = mid + 1;
} else {
// [5] Too few pieces, so every longer length gives too few. mid may be the first length that fails, so keep it: hi moves to it.
hi = mid;
}
}
// [6] The window is empty: lo is the first length that fails, so lo - 1 is the longest length that works. It is 0 when none works.
return lo - 1;
}To find the largest candidate that works, search for the first candidate that fails, and subtract one.
Exercise · Find the bug: The longest ribbon is never tried. This search finds the longest whole piece length that gives at least k pieces, or 0 when none does. For some inputs it answers one less than it should. Which line is wrong?
def longest_piece(ribbons, k):
lo = 1
hi = max(ribbons)
while lo < hi:
mid = lo + (hi - lo) // 2
pieces = 0
for r in ribbons:
pieces += r // mid
if pieces >= k:
lo = mid + 1
else:
hi = mid
return lo - 1A craft store has ribbons of lengths 9, 7 and 5. It wants at least 6 pieces of one equal length, and it wants the pieces as long as possible. What is the longest length?
At a length L the ribbons give 9 / L, 7 / L and 5 / L pieces, each rounded down. The totals for L = 1 to 10 are 21, 9, 6, 4, 3, 2, 2, 1, 1 and 0. The check "at least 6 pieces" reads yes, yes, yes, no, no, no, no, no, no, no: it passes and then fails, which is monotone.
The range is lo = 1 and hi = 10, the longest ribbon plus 1, which gives 0 pieces and fails. The search checks 5, which fails, so hi moves to 5. It checks 3, which passes, so lo moves to 4, and then 4, which fails, so hi moves to 4. It ends with lo = 4, the first length that fails, so the answer is 3.
Exercise · Predict the output: Which lengths does the search try?. Ribbons of 8, 5 and 11 are cut into pieces of equal length, and we want at least 7 pieces as long as possible. The code prints every length it tries, then its answer. What does it print?
ribbons = [8, 5, 11]
k = 7
lo, hi = 1, max(ribbons) + 1
tried = []
while lo < hi:
mid = lo + (hi - lo) // 2
tried.append(mid)
pieces = 0
for r in ribbons:
pieces += r // mid
if pieces >= k:
lo = mid + 1
else:
hi = mid
print(*tried, lo - 1)The checks add up numbers. The hours needed can reach 10^5 files × 10^7 blocks = 10^12. For ribbons up to 10^9 long, the pieces can reach about 10^14.
In Java and C++, a 32-bit int holds at most 2,147,483,647, so the sum needs a 64-bit integer: long in Java and long long in C++. The same goes for hi when it is a sum of loads. Python integers never overflow, and JavaScript numbers are exact up to 2^53, about 9 × 10^15, which is above these sums.
lo, hi and mid, and the check keeps a running total, so the extra space is O(1).Real production data brings edge cases.
For sizes = [7] and hours = 1, the window is [1, 7). Every rate below 7 needs more than one hour, so the search ends at 7. For hours = 7, the answer is 1.
For sizes = [5, 9, 2] and hours = 3, every file must take one hour, so the rate must reach the largest file. No check below 9 passes, and the search returns hi, which is 9. The check never ran at 9: it was known to work.
For sizes = [3, 3, 3] and hours = 9, the rate 1 already fits, so every check passes and the search ends at lo, which is 1.
For the split with loads = [4, 9, 3, 7, 2, 8], k = 1 gives the sum, 33, and k = 6 gives the largest load, 9. These are exactly the two bounds of the range.
Exercise · Break it: Find the file that costs an extra hour. This search finds the slowest whole rate that uploads every file within the given hours. Its hours check adds r to a file size before it divides. Find an input where it gives the wrong answer.
def slowest_rate(sizes, hours):
lo = 1
hi = max(sizes)
while lo < hi:
mid = lo + (hi - lo) // 2
needed = 0
for s in sizes:
needed += (s + mid) // mid
if needed <= hours:
hi = mid
else:
lo = mid + 1
return loThis version computes the hours of a file as s // r and forgets to round up. It thinks that a file of 14 blocks takes 0 hours at rate 15.
Counterexample: sizes = [40, 12, 27, 5, 18] and hours = 9. With the rounded-down check the search returns 10, but at rate 10 the files really need 12 hours. The correct answer is 14.
A common mistake: rounding the hours down. A file that needs part of an hour still takes a whole hour, so rounding down makes slow rates look fast.
This version splits loads into runs, and starts the search at lo = 1. A load heavier than L gets a run of its own, as if it fitted, so impossible values of L pass the check.
Counterexample: loads = [5, 9, 2, 4] and k = 3. The search returns 6, and no run may hold the 9 with a load limit of 6. The correct answer is 9, which is the largest load, so lo must start there.
This version, in Java, writes int hi = sum of the loads for the split search. The sum of two loads of 1,500,000,000 is 3,000,000,000, which is above 2,147,483,647, so it wraps to -1,294,967,296.
Counterexample: loads = [1500000000, 1500000000] and k = 1. With hi negative the loop never runs, and the search returns lo, which is 1,500,000,000. The correct answer is 3,000,000,000, which needs a long. In C++ the overflow is undefined behaviour, so the result is not guaranteed at all.
This version searches for the largest length with the first-true template, and tests "at least k pieces" as the condition. That condition is true for small lengths and false for large ones, so it is true and then false.
Counterexample: ribbons = [9, 7, 5] and k = 6. The search checks length 5, which gives 3 pieces, so the condition is false and lo moves to 6. It ends at 10, the end of the window, but the correct answer is 3. Search for the first length that fails, and subtract 1.
Your team lead asks for the slowest rate at which the files take exactly 9 hours, and not at most 9. The files are [10, 10, 10]. The hours are 30, 15, 12, 9, 6, 6, 6, 6, 6 and 3 for the rates 1 to 10. Only the rate 4 takes exactly 9 hours.
The check "exactly 9" is false, then true at 4, then false again. The search checks rate 5, which needs 6 hours, so the check is false and lo moves to 6. It ends at 10, which needs 3 hours, and the answer 4 is lost. Ask for "at most 9" and the search finds 4.
A common mistake: a check such as exactly 9 hours. It is false, then true, then false, so the search can miss the answer.
Your team lead brings four product changes. Each one asks what the candidates are, and what the check is.
A parcel app ships parcels in order, and each day one truck takes the next parcels up to its capacity. The smallest capacity that ships everything within d days is the split search, with days in place of runs. See LeetCode 1011: Capacity To Ship Packages Within D Days, and LeetCode 410: Split Array Largest Sum.
A store grows flowers, and a bouquet needs k neighbouring flowers that have bloomed. The candidates are the days, and the check counts the bouquets that the bloomed flowers allow. More days never give fewer bouquets (LeetCode 1482: Minimum Number of Days to Make m Bouquets).
A parcel app places k lockers along a road and wants the closest pair as far apart as possible. The candidates are the gaps. The check scans the sorted spots from the left, and places a locker at each spot that is at least that far from the last one. A smaller gap never fits fewer lockers, so this is a largest search (LeetCode 1552: Magnetic Force Between Two Balls).
A table of pair gaps is too big to build. The candidates are the gap values, and the check counts the pairs with a gap of at most the candidate. The first candidate that counts at least k pairs is the k-th smallest gap (LeetCode 719: Find K-th Smallest Pair Distance).
Explain it back: write the idea in your own words and get feedback.
In two or three sentences, explain to a teammate how you find the slowest upload rate without trying every rate. Then explain what you must prove before you may use the search. The AI tutor checks your answer against the invariant and the key points of this lesson.
Here is how you could explain it in an interview, now that you have built it.
I do not search a list. I search the possible rates, and I write a check that says whether one rate finishes in time.
A faster rate never needs more hours, so the check is false and then true. That is the first-true template, on the numbers 1 to the largest file.
I state the range: 1 is the lowest rate, and the largest file's rate certainly works. Each check is one pass over the queue, so it costs O(n log range).
The straightforward answer tries every candidate, and each try reads the whole input. When the answer is a number, and a bigger candidate never hurts, I search the candidates instead.
I write a check that tests one candidate. Then I prove it flips once: if a candidate works, every larger one works too. That makes it a first-true search over the candidates.
I state the range. The low bound is the smallest candidate that could work. The high bound is a candidate that certainly works, or one past the largest candidate for a largest search.
The cost is the number of checks, log of the range, times the cost of one check, usually one pass over the input.
I use a 64-bit integer for sums, and I say why a check such as exactly H would break the search.
Checkpoint · The check and the range
Q1/4 You search on the answer with a check that tests one candidate. What must be true of the check for the first-true template to work?
Answer: B
The template needs one flip: false, then true for ever. A cheap check is nice, but it does not make the search correct. The candidates can be plain numbers, with no list.
Q2/4 The files are [40, 12, 27, 5, 18] and the window is 9 hours. At the rate 10 the files need 12 hours. What does the search do?
Answer: B
12 hours is more than 9, so the rate 10 is too slow, and every slower rate is too. Rule it out with lo = mid + 1.
Q3/4 Why is the rate of the largest file a safe starting hi for the slowest-rate search?
Answer: B
At that rate each file takes exactly one hour, whatever its size. A faster rate cannot do better, so the answer is not above it.
Q4/4 At the rate 15, how many hours does a file of 14 blocks take, when the uploader starts a file only at the top of the hour?
Answer: B
The file takes 14 / 15 of an hour, rounded up to a whole hour, which is 1. Rounding down gives 0 and makes slow rates look fast.
Checkpoint · Splits, largest searches and limits
Q1/4 In the split search, why does lo start at the heaviest single load?
Answer: C
A load limit below the heaviest load cannot fit that load in any run. Starting lower lets impossible limits pass, as in the exhibit with 5, 9, 2 and 4.
Q2/4 The ribbons are [9, 7, 5] and you want the longest length that gives at least 6 pieces. Which search finds it?
Answer: B
Pieces are enough for short lengths and too few for long ones, so the check passes and then fails. Search for the first length that fails, and the answer is the one before it.
Q3/4 The ribbon search ends with lo = 4, the first length that gives fewer than 6 pieces. What is the longest length that gives at least 6 pieces?
Answer: B
lo is the first length that fails, so the longest length that works is lo - 1, which is 3. At length 3 the ribbons give 3 + 2 + 1 = 6 pieces.
Q4/4 In Java, the sum of the loads [1500000000, 1500000000] is stored in an int and used as hi. What is the fix?
Answer: B
The sum 3,000,000,000 is above 2,147,483,647, so an int wraps to a negative number and the loop never runs. A long holds it. Python and JavaScript need no change for these sizes.
Checkpoint · When it breaks
Q1/2 Which check would break a search on the answer, and give a wrong result?
Answer: C
"Exactly 9 hours" is false, then true for the rates that take 9 hours, then false again. It does not flip once. The other checks are monotone.
Q2/2 The queue holds 100,000 files, and the answer can be as large as 10^7. About how many checks does the search make, in the worst case?
Answer: C
The window holds up to 10^7 rates and halves at every step, so the search makes at most floor(log2 of that) + 1 checks, which is 24. Each check reads the 100,000 files once.
Ten questions on this lesson. Pass with 80% or more to be sure the idea has landed before the next lesson.
| Step | Problem | Product line | Level | What it practises |
|---|---|---|---|---|
| 1 | Slowest rate that still finishes | Social | Medium | A sum of rounded-up hours as the check |
| 2 | Smallest capacity that ships in d days | Parcels | Medium | A greedy pass over parcels in order as the check |
| 3 | Earliest day for m bouquets | Store | Medium | Counting groups of neighbours as the check |
| 4 | Minimum time for all trips | Rides | Medium | A sum of whole trips as the check, and a large answer |
Review cards from this lesson.
Five cards from this lesson join your spaced-review deck. The first one comes back tomorrow.
Step through the idea on your own input, then build it in the lab. Runs in your browser. Step through it.
A few questions, then explain the idea back in your own words. Your tutor marks it. Quiz and explain back.