Find the first position where a condition becomes true, with no infinite loops.
Use it when a condition is false for some positions and then true for ever, and you want the first position where it is true. Signal words: the first one that, from some point on, once it breaks it stays broken, the smallest position where.
Start lo = 0 and hi = n, one past the last position. The window [lo, hi) holds the positions still in question.
Step while lo < hi, check mid = lo + (hi - lo) / 2. If the condition is false at mid, set lo = mid + 1. Otherwise set hi = mid.
Stop when lo == hi. The answer is lo, and lo == n means that no position is true.
It does not work when the condition can switch back from true to false. One flip is needed.
Cost: at most floor(log2 n) + 1 checks, O(log n), and O(1) extra space. The scan costs O(n) checks.
In this lesson you learn to find the first position where a condition becomes true, in a list or in a range of numbers. You keep a window of positions that are still in question, you check its middle, and you cut away half. You also learn how to write it so that it never loops for ever.
You work on the build system of a monitoring app. The checkout service has had 1,000 builds since its last quiet week, numbered 0 to 999. One change broke the health check.
That build fails the check, and so does every later build, because the break stays in the code. Every build before it passes.
Running the health check on one build takes 6 minutes.
Your team lead says: Find the first failing build today. Nobody wants to wait for the nightly run.
Here is a short test: 12 builds, numbered 0 to 11. Builds 0 to 7 pass and builds 8 to 11 fail, so the answer is build 8.
So the task is this: find the first failing build with as few test runs as you can.
A power fault switched off the street lamps on a long road, from some lamp to the end. The lamps before that lamp are on. You want the first lamp that is off.
You can drive to any lamp and look at it, but each trip takes time. So you drive to the lamp in the middle of the road. If it is on, the fault starts further along, and you can ignore every lamp before it.
If it is off, the first dark lamp is this one or an earlier one, and you can ignore every lamp after it. Each look rules out half of the lamps still in question. The lamps are the builds, and one look is one test run.
Like finding the first dark lamp on a road: look at the middle lamp, and the answer tells you which half of the road to ignore.
Before you write code, solve the test by hand. It shows how many test runs you need.
Solve it by hand: Twelve builds: find the first failing build. The hand-solve sheet loads in your browser.
You start at build 0 and run the check on each build in turn. You stop at the first build that fails.
Results: builds 0 to 7 pass, and builds 8 to 11 fail.
| Check number | Build | Result | What you learn |
|---|---|---|---|
| 1 | 0 | passes | the first failing build is later |
| 2 | 1 | passes | the first failing build is later |
| 3 to 8 | 2 to 7 | pass | the first failing build is later |
| 9 | 8 | fails | build 8 is the first failing build |
You made 9 checks. If no build had failed, you would have made all 12 checks.
Look at what grows. A list of n builds needs up to n checks.
Start with a correct version. Check the builds in order, and stop at the first one that fails.
def first_failing(results):
for i in range(len(results)): # every build, from the first
if results[i] == 1: # one test run of build i
return i
return -1Here results[i] stands for one test run of build i: 0 if it passes and 1 if it fails. This is correct. It makes up to n checks: O(n). The team keeps it as the reference.
Now check the real size.
The checkout service has 1,000 builds, and one check takes 6 minutes.
Here is the count:
So the answer arrives after days, and the team cannot find the bad change today.
Predict the cost
Q The first failing build is build 999 of 1,000, and each check takes 6 minutes. About how long does the first attempt take?
Answer: C
The scan checks builds 0 to 999, which is 1,000 checks. 1,000 × 6 minutes is 6,000 minutes, or 100 hours: more than 4 days, but not 10.
The first attempt is correct, but it ignores a fact about the builds. Now the team uses it.
Look at the results again: pass, pass, pass, and then fail, fail, fail. There is exactly one flip. When a break stays in the code, a failing build is never followed by a passing one.
A condition that is false for some positions and then true for ever is called a monotone condition. The first position where it is true is the answer. You can find it without checking every position, because one check tells you a lot.
Check the build in the middle:
Either way, one check rules out about half of the builds that are still in question.
To keep track, hold a half-open window [lo, hi). It is written with a square bracket on the left and a round bracket on the right. Build lo is in the window, and build hi is not. The window starts as [0, 12), which is every build.
| Step | Window | Middle build | Result | New window |
|---|---|---|---|---|
| 1 | [0, 12) | 6 | passes | [7, 12) |
| 2 | [7, 12) | 9 | fails | [7, 9) |
| 3 | [7, 9) | 8 | fails | [7, 8) |
| 4 | [7, 8) | 7 | passes | [8, 8) |
The window [8, 8) is empty, and its left end is 8. That is the first failing build. The search made 4 checks, and the scan made 9.
Race: Check every build from the first, against the window search. The operation counter loads in your browser.
The race counts the worst case. At 1,000 builds the scan makes 1,000 checks, which is 100 hours, and the window search makes 10, which is 1 hour. At 10,000 builds the scan needs 10,000 checks and the window search needs 14. Each check doubles the size of the list the search can handle.
One check of the middle build rules out about half of the builds still in question, because a failing build never precedes a passing one.
The results are [0, 0, 0, 1, 1, 1, 1, 1, 1, 1]: ten builds, and the first failing build is build 3. The player stops at six steps and asks you to predict.
Dry run: Predict each step: ten builds, the first failure at build 3. 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 | Result of build mid | What moves |
|---|---|---|---|---|---|
| 1 | 0 | 10 | 5 | fails | hi moves to 5 |
| 2 | 0 | 5 | 2 | passes | lo moves to 3 |
| 3 | 3 | 5 | 4 | fails | hi moves to 4 |
| 4 | 3 | 4 | 3 | fails | hi moves to 3 |
| end | 3 | 3 | none | the window is empty, so return 3 |
Look at step 1. The middle of [0, 10) is build 5, and it fails. Build 5 might still be the first failing build, so hi moves to 5 and not to 4.
The end of the search is where most mistakes hide, so look at the last two steps of the table above.
At step 3 the window is [3, 5). It holds builds 3 and 4, and the middle is build 4. Build 4 fails, so hi moves to 4.
At step 4 the window is [3, 4). It holds one build, build 3, so the middle is build 3 itself. It fails, so hi moves to 3.
Now lo == hi == 3, the window is empty, and the loop stops. The answer is lo.
A window of one build always has its middle on that build. That is why the search always reads a real build, and never build hi. It is also why a failing build must stay in the window: here, build 3 was the answer, and it was still in the window at step 4.
The last two steps: a window of two builds shrinks to one, the middle sits on that build, and a failing build stays in the window.
Here is the rule that keeps the search correct. Every line of the template exists to protect it.
Every position before lo is false and every position from hi on is true, counting n as true, so the first true position lies between lo and hi.
At the start lo = 0 and hi = n. No position is before 0, and no real position is from n on, so the rule holds. Say it holds, and look at the middle, mid. The middle is always a real position inside the window, as the section on termination shows.
If the condition is false at mid, then every position up to mid is false, because the condition never goes back from true to false. So lo = mid + 1 keeps the rule. If it is true at mid, then every position from mid on is true, so hi = mid keeps the rule.
When lo == hi, nothing is left in question. Everything before lo is false and everything from lo on is true, so lo is the first true position. If lo == n, no real position is true.
Let s = hi - lo be the size of the window. The loop runs while s is at least 1. The middle is mid = lo + s / 2, with the division rounded down. For s >= 1 that is at least lo and at most hi - 1, so mid is always a real position inside the window.
After one step the new size is either mid - lo, which is s / 2 rounded down, or hi - (mid + 1), which is s - s / 2 - 1, also at most s / 2 rounded down. So every step at least halves the window and the size reaches 0.
The number of checks is at most floor(log2 n) + 1. For 1,000 builds that is 10, and for a billion builds it is 30. Moving lo to mid instead would not shrink a window of size 1, and the loop would never end.
Exercise · Predict the output: Which positions does the search check?. Seven builds, where 0 passes and 1 fails. The loop prints each mid it checks, then the final lo. What does it print?
results = [0, 0, 0, 0, 1, 1, 1]
lo, hi = 0, len(results)
mids = []
while lo < hi:
mid = lo + (hi - lo) // 2
mids.append(mid)
if results[mid] == 0:
lo = mid + 1
else:
hi = mid
print(*mids, lo)Use it when a condition is false for some positions and then true for ever, and you want the first position where it is true. Signal words: the first one that, from some point on, once it breaks it stays broken, the smallest position where.
Start: lo = 0 and hi = n, one past the last position. The window [lo, hi) holds the positions still in question.
Step: while lo < hi, check mid = lo + (hi - lo) / 2. If the condition is false at mid, set lo = mid + 1. Otherwise set hi = mid.
Stop: when lo == hi. The answer is lo, and lo == n means that no position is true.
It does not work when the condition can switch back from true to false. One flip is needed.
Cost: at most floor(log2 n) + 1 checks, O(log n), and O(1) extra space. The scan costs O(n) checks.
def first_failing(results):
# [1] The window [lo, hi): builds before lo pass, builds from hi on fail, and build n counts as failing.
lo = 0
hi = len(results)
# [2] While the window holds a build, check the build in its middle.
while lo < hi:
mid = lo + (hi - lo) // 2
if results[mid] == 0:
# [3] A passing build rules out itself and every build before it, so lo moves past it.
lo = mid + 1
else:
# [4] A failing build may be the first, so keep it: hi moves to it.
hi = mid
# [5] The window is empty: lo is the first failing build, or -1 when no build failed.
return lo if lo < len(results) else -1public int firstFailing(int[] results) {
// [1] The window [lo, hi): builds before lo pass, builds from hi on fail, and build n counts as failing.
int lo = 0;
int hi = results.length;
// [2] While the window holds a build, check the build in its middle.
while (lo < hi) {
int mid = lo + (hi - lo) / 2;
if (results[mid] == 0) {
// [3] A passing build rules out itself and every build before it, so lo moves past it.
lo = mid + 1;
} else {
// [4] A failing build may be the first, so keep it: hi moves to it.
hi = mid;
}
}
// [5] The window is empty: lo is the first failing build, or -1 when no build failed.
return lo < results.length ? lo : -1;
}int firstFailing(vector<int>& results) {
// [1] The window [lo, hi): builds before lo pass, builds from hi on fail, and build n counts as failing.
int lo = 0;
int hi = (int)results.size();
// [2] While the window holds a build, check the build in its middle.
while (lo < hi) {
int mid = lo + (hi - lo) / 2;
if (results[mid] == 0) {
// [3] A passing build rules out itself and every build before it, so lo moves past it.
lo = mid + 1;
} else {
// [4] A failing build may be the first, so keep it: hi moves to it.
hi = mid;
}
}
// [5] The window is empty: lo is the first failing build, or -1 when no build failed.
return lo < (int)results.size() ? lo : -1;
}function firstFailing(results) {
// [1] The window [lo, hi): builds before lo pass, builds from hi on fail, and build n counts as failing.
let lo = 0;
let hi = results.length;
// [2] While the window holds a build, check the build in its middle.
while (lo < hi) {
const mid = lo + Math.floor((hi - lo) / 2);
if (results[mid] === 0) {
// [3] A passing build rules out itself and every build before it, so lo moves past it.
lo = mid + 1;
} else {
// [4] A failing build may be the first, so keep it: hi moves to it.
hi = mid;
}
}
// [5] The window is empty: lo is the first failing build, or -1 when no build failed.
return lo < results.length ? lo : -1;
}Rebuild the template: put its lines back in order. Loads in your browser.
Exercise · Find the bug: The failing build that gets skipped. This search for the first failing build returns a build that passed, on some inputs. Which line is wrong?
def first_failing(results):
lo, hi = 0, len(results)
while lo < hi:
mid = lo + (hi - lo) // 2
if results[mid] == 0:
lo = mid + 1
else:
hi = mid - 1
return lo if lo < len(results) else -1The template in order: check the middle, move lo past a passing build, keep a failing build, and stop when the window is empty.
The template does not change. Only two things change from one question to the next, and you can answer them before you write any code.
0 to n - 1 of a list, or the whole numbers of a range. Write the window so that the last candidate is hi - 1, and hi stands for "none of them".mid? It must be false before the answer and true from it on. Write it as a test that uses mid.Then check the two ends: what does the search return when the condition is never true, and when it is always true?
Exercise · Break it: Find the input this search gets wrong. This search for the first failing build starts with hi = n - 1. Find a list of results where it gives the wrong answer.
def first_failing(results):
lo, hi = 0, len(results) - 1
while lo < hi:
mid = lo + (hi - lo) // 2
if results[mid] == 0:
lo = mid + 1
else:
hi = mid
return lo| Question | Candidates | Condition at mid |
|---|---|---|
| The first failing build | builds 0 to n - 1, with hi = n for none |
the build fails: results[mid] == 1 |
| Where a new value goes in a sorted list | positions 0 to n - 1, with hi = n for the end |
the value is at least the new one: values[mid] >= target |
| The first day a growing total reaches a goal | days 0 to the goal | the total is at least the goal: total(mid) >= goal |
The largest whole number whose square fits in a (a last) |
the numbers 0 to a, with hi = a + 1, whose square is always too big |
the square is too big: mid * mid > a, and the answer is lo - 1 |
In the code, the false case is the one that moves lo. For the build question, "false" means that the build passes, which is why the template tests results[mid] == 0.
Here the list holds numbers in sorted order, and the condition compares each number with a target. A sorted list is monotone for this question: the values below the target come first, and the rest follow.
def first_at_least(values, target):
# [1] The window [lo, hi): values before lo are below the target, values from hi on are not, and position n counts as not below.
lo = 0
hi = len(values)
# [2] While the window holds a position, look at the value in its middle.
while lo < hi:
mid = lo + (hi - lo) // 2
if values[mid] < target:
# [3] A value below the target rules out itself and every value before it, so lo moves past it.
lo = mid + 1
else:
# [4] A value that is not below may be the first, so keep it: hi moves to it.
hi = mid
# [5] The window is empty: lo is the first position whose value is at least the target, or n.
return lopublic int firstAtLeast(int[] values, int target) {
// [1] The window [lo, hi): values before lo are below the target, values from hi on are not, and position n counts as not below.
int lo = 0;
int hi = values.length;
// [2] While the window holds a position, look at the value in its middle.
while (lo < hi) {
int mid = lo + (hi - lo) / 2;
if (values[mid] < target) {
// [3] A value below the target rules out itself and every value before it, so lo moves past it.
lo = mid + 1;
} else {
// [4] A value that is not below may be the first, so keep it: hi moves to it.
hi = mid;
}
}
// [5] The window is empty: lo is the first position whose value is at least the target, or n.
return lo;
}int firstAtLeast(vector<int>& values, int target) {
// [1] The window [lo, hi): values before lo are below the target, values from hi on are not, and position n counts as not below.
int lo = 0;
int hi = (int)values.size();
// [2] While the window holds a position, look at the value in its middle.
while (lo < hi) {
int mid = lo + (hi - lo) / 2;
if (values[mid] < target) {
// [3] A value below the target rules out itself and every value before it, so lo moves past it.
lo = mid + 1;
} else {
// [4] A value that is not below may be the first, so keep it: hi moves to it.
hi = mid;
}
}
// [5] The window is empty: lo is the first position whose value is at least the target, or n.
return lo;
}function firstAtLeast(values, target) {
// [1] The window [lo, hi): values before lo are below the target, values from hi on are not, and position n counts as not below.
let lo = 0;
let hi = values.length;
// [2] While the window holds a position, look at the value in its middle.
while (lo < hi) {
const mid = lo + Math.floor((hi - lo) / 2);
if (values[mid] < target) {
// [3] A value below the target rules out itself and every value before it, so lo moves past it.
lo = mid + 1;
} else {
// [4] A value that is not below may be the first, so keep it: hi moves to it.
hi = mid;
}
}
// [5] The window is empty: lo is the first position whose value is at least the target, or n.
return lo;
}Compare it with Template 1. The loop is the same, and only the test in line [3] is new. The next lesson gives this search a name, the lower bound, and builds on it.
Exercise · Put it in order: Where does a new id go?. Arrange the lines into a search that returns the first position whose id is at least the target, or the list length when none is.
def insertion_point(ids, target):
lo = 0
hi = len(ids)
while lo < hi:
mid = lo + (hi - lo) // 2
if ids[mid] < target:
lo = mid + 1
else:
hi = mid
return lo
hi = len(ids) - 1A rewards screen in a payments app gives 1 point on day 1 of a streak, 2 points on day 2, 3 on day 3, and so on. After d days the total is d × (d + 1) / 2. On which day does the total first reach 20 points?
There is no list. The candidates are the numbers of days, 0 to 20. The total after 20 days is 210, so the answer is certainly in that range, and the window [0, 21) holds every candidate. Only the condition is new: mid * (mid + 1) / 2 >= 20.
| Step | lo | hi | mid | Total after mid days | What moves |
|---|---|---|---|---|---|
| 1 | 0 | 21 | 10 | 55 | 55 is at least 20, so hi moves to 10 |
| 2 | 0 | 10 | 5 | 15 | 15 is below 20, so lo moves to 6 |
| 3 | 6 | 10 | 8 | 36 | hi moves to 8 |
| 4 | 6 | 8 | 7 | 28 | hi moves to 7 |
| 5 | 6 | 7 | 6 | 21 | hi moves to 6 |
| end | 6 | 6 | day 6 |
The answer is day 6, because the total after 5 days is 15 and after 6 days it is 21. The search made 5 checks. For a goal near a billion, the total passes the 32-bit limit, so Java and C++ need a 64-bit integer for it.
The middle of lo and hi can be written two ways. They are equal in mathematics, but not always in a computer.
Take a search over the numbers 0 to 2,000,000,000, for example bytes or milliseconds. After a few steps lo is 1,500,000,000 and hi is 2,000,000,000.
lo + hi is 3,500,000,000. That is above 2,147,483,647, the largest 32-bit integer.hi - lo is 500,000,000, and lo + (hi - lo) / 2 is 1,750,000,000. The difference never passes hi, so it cannot overflow.| Language | (lo + hi) / 2 |
lo + (hi - lo) / 2 |
|---|---|---|
| Java | 32-bit int: the sum wraps to a negative number |
safe |
| C++ | 32-bit int: the same, and signed overflow is undefined behaviour |
safe |
| JavaScript | numbers are 64-bit floating point, so the sum is exact up to 2^53 (about 9 × 10^15), but the result can have a fraction: use Math.floor. Halving with >> 1 turns the sum into a 32-bit integer first, so it wraps like Java |
safe: lo + Math.floor((hi - lo) / 2) |
| Python | integers have no limit, so no overflow | safe, and (lo + hi) // 2 is also fine |
For positions in a list, the sum only overflows when the list holds more than a billion items. For a search over answers, a range of two billion is easy to reach. So the lesson templates write lo + (hi - lo) / 2 in every language, and the habit is safe everywhere.
Some practice solutions write (lo + hi) // 2 in Python, or (lo + hi) >> 1 in JavaScript on list positions, which is safe there, because the sum stays far below 2^31. Java programmers also write (lo + hi) >>> 1 for values that are never negative, which works because the wrapped sum is read as an unsigned number.
lo, hi and mid, so it needs O(1) extra space.Real production data brings edge cases.
Before the first build, results = []. The window is [0, 0), the loop never runs, and lo is 0, which equals n. The template returns -1: nothing failed.
For results = [0, 0, 0], every middle build passes, and lo moves to 3. Then lo == n, so the template returns -1. The answer "none" is possible only because hi starts at n and not at n - 1.
For results = [1, 1, 1], every middle build fails, and hi moves down to 0. The window is [0, 0) and the answer is 0: the very first build is the first failing build.
For results = [1], the window is [0, 1), the middle is build 0, it fails, and hi becomes 0. The answer is 0. For results = [0], build 0 passes, lo becomes 1, and the answer is -1. A window of one build must end in one step.
This version writes lo = mid when the build passes, as if mid were still in question. A passing build is ruled out, so lo must move past it.
Counterexample: results = [0]. The window is [0, 1), the middle is 0, and build 0 passes. The bug sets lo = 0, which changes nothing. The window never shrinks, so the loop runs for ever.
The fix is lo = mid + 1. A step that does not shrink the window can never end.
A common mistake: setting lo to mid when the middle build passes. With one passing build the window never shrinks, so the loop runs for ever.
This version writes while lo <= hi, the test for a closed window that includes hi. Here the window is [lo, hi), so it is empty when lo == hi. With <=, an empty window is searched once more.
Counterexample: results = [1]. The first step sets hi = 0. The window [0, 0) is empty, but 0 <= 0 lets the loop run again with mid = 0. Build 0 fails, hi stays 0, and the loop runs for ever.
With results = [0] it moves lo to 1 and then reads build 1, which is past the end.
Pick one window convention and use the matching test. This course uses [lo, hi) and lo < hi.
This version starts with hi = n - 1, as many closed-window versions do. Build n - 1 is then never in the window, and the search can never answer "none".
Counterexample: results = [0, 0, 0]. The window is [0, 2). The middle is 1 and it passes, so lo becomes 2 and the loop ends. Since 2 < 3, the code returns 2, but no build failed, and the right answer is -1.
Start with hi = n. Position n counts as true, and it is what makes "none" an answer.
This version writes mid = (lo + hi) / 2 in Java or C++ and searches the whole numbers from 0 to 2,000,000,000 for the first one that is at least 1,800,000,000.
Counterexample: the first step has lo = 0 and hi = 2,000,000,000, and the middle is 1,000,000,000. It is below the target, so lo becomes 1,000,000,001. The next sum is 3,000,000,001, which wraps to a negative number, so mid is -647,483,647 and lo moves back to -647,483,646.
From then on lo jumps between negative and positive values, and hi never moves. A run in Java never ends: after 30 steps, lo repeats the same two values for ever.
The fix is lo + (hi - lo) / 2, which finds 1,800,000,000 in 30 checks.
Your team lead asks for the first build that failed, but the results come from a flaky test. The results read [0, 1, 0, 0, 1, 1]: build 1 failed, then passed again. The condition is true, then false, then true.
The search checks build 3, which passes, so it moves lo to 4 and returns build 4. The first failing build was build 1. The rule "a passing build rules out everything before it" is false for a flaky test. This pattern needs one flip, and a flaky history needs a different method.
Your team lead brings four product changes. Each one asks what the candidates are, and what the condition is.
A support tool keeps ticket ids in sorted order, and needs the position for a new id. The condition is "this id is at least the new one", so this is Template 2 (LeetCode 35: Search Insert Position).
A feed returns items by position, but you do not know how many there are. Start with hi = 1 and double it until the item at hi is past the value you want, or the position is past the end. Then search the window below hi with the template. That takes about 2 log n checks (LeetCode 702: Search in a Sorted Array of Unknown Size).
A chart needs the whole-number square root of an amount. The candidates are the whole numbers, and the condition is "its square is above the amount". The first such number minus 1 is the root (LeetCode 69: Sqrt(x)). Use a 64-bit integer for the square.
A dashboard shows how many builds failed since the last quiet week. The failing builds are the last ones, so the count is n - first when a build failed, and 0 when none did. One search gives the count without reading every build.
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 first position where a condition becomes true. Then explain why moving lo to mid + 1, and hi to mid, never loops for ever. 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 keep a window of positions that are still in question. Everything before it fails the condition, and everything after it passes. I check the middle of the window.
If the condition is false there, I move the left end past it. If it is true, I move the right end to it, because it may be the first. The window at least halves each step, so the loop ends.
When the window is empty, its left end is the answer, and the end of the list means none. That is log n checks.
The straightforward answer checks every position from the start, which costs n checks. When the condition is false for a while and then true for ever, I can do much better with a binary search.
I keep a window from lo up to, but not including, hi. Every position before lo is false, and every position from hi on is true, where position n counts as true. I start with lo at 0 and hi at n.
I check the middle, written as lo plus half of hi minus lo, so that it cannot overflow. If the condition is false there, lo moves to mid plus 1. If it is true, hi moves to mid, because mid may be the answer.
Each step halves the window, so it ends. When lo equals hi, lo is the answer, and n means none.
That is about log n checks. It needs one flip, so a flaky condition needs another method.
Checkpoint · The idea
Q1/3 Which question can the first-true template answer?
Answer: C
The total never goes down, so "the total is at least 500" is false for a while and then true for ever. The other three questions have no single flip.
Q2/3 In the window [lo, hi), what does the invariant say?
Answer: B
Positions before lo are ruled out because they are false, and positions from hi on are known to be true. The positions from lo up to, but not including, hi are still in question.
Q3/3 The window is [0, 8). What is mid, with mid = lo + (hi - lo) / 2?
Answer: B
The size of the window is 8 - 0 = 8, and half of it is 4, so mid = 0 + 4 = 4. It is a position inside the window.
Checkpoint · The moves
Q1/3 The condition is true at mid. What do you do?
Answer: B
A true position may still be the first one, so it stays in the window as its new end: hi = mid. Everything after mid is true too, so those positions cannot be the first.
Q2/3 The window is [5, 6) and the condition is false at position 5. What is the window after the step?
Answer: B
A false position is ruled out, so lo = mid + 1 = 6. The window [6, 6) is empty, and 6 is the answer: the first true position is after 5.
Q3/3 Why does the loop always end?
Answer: C
The middle is at least lo and below hi, so both moves remove at least half of the window, rounded down. A step that moved lo to mid would not shrink a window of size 1, and that loop would never end.
Checkpoint · Edges and cost
Q1/4 A version starts with hi = n - 1 and the window [lo, hi). For results = [0, 0, 0], where no build fails, what does it return?
Answer: C
The window is [0, 2). The middle is 1 and it passes, so lo becomes 2 and the loop ends. Since 2 is below 3, the code returns 2, but no build failed. Starting with hi = n keeps "none" possible.
Q2/4 A service has 1,000 builds. At most how many checks does the template make?
Answer: C
At most floor(log2 1,000) + 1 checks: 2^9 is 512 and 2^10 is 1,024, so 10 are enough. The scan could need 1,000.
Q3/4 In Java, lo is 1,500,000,000 and hi is 2,000,000,000. Which middle is safe?
Answer: C
The sum is 3,500,000,000, which is above 2,147,483,647, so a 32-bit int wraps to a negative number. The difference is small, and adding half of it to lo never passes hi. Python integers do not overflow.
Q4/4 The results are [0, 1, 0, 0, 1, 1] because a test is flaky. Why can you not trust the template here?
Answer: C
The template relies on the condition being false and then true for ever. With one flip, a passing middle means everything before it passes. Here build 3 passes, but build 1 failed before it.
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 | Find the first failing build | Platform | Easy | The template on a row of 0s and 1s, for many questions |
| 2 | Insertion point for a new id | Shop | Easy | The condition becomes a comparison with a target, and repeats |
| 3 | Integer square root | Payments | Easy | No list at all: the window holds the possible answers |
| 4 | First day the spend limit is reached | Bank | Medium | The list is built first, from running totals |
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.