Bisect a version history with flaky checks, and answer what a value was at a past time by searching timestamps.
Use it when the versions are in order, a bad version stays bad, and you can test one version. Signal words: the first bad version, the first time a limit was passed, bisect.
Start lo is 0. hi is the number of versions, or a version known to be bad.
Step while lo < hi, set mid = lo + (hi - lo) / 2 and test version mid. If it is bad, set hi = mid. Otherwise set lo = mid + 1.
Stop when lo == hi. The answer is lo. If lo is the number of versions, no version is bad.
It does not work when a bad version can become good again, or when a test result can be wrong in both directions.
Cost: log2 of the number of versions, plus 1, tests, each costing its repeated runs.
In this lesson the sorted thing is a history. You bisect a list of versions with a test that is flaky, and you look up what a value was at a past time. Both are the first-true template on an order that time gives you.
You work on the release pipeline of a payments app. It has shipped 100,000 versions. A bug entered one version and stays in every later one. Each version has a smoke test, and the test is flaky.
On a good version the test never fails. On a bad version it fails in some runs only. So every version is run up to 5 times, and one run takes 6 minutes.
Your team lead says: Find the first bad version. And when the audit team gives you a time, tell me which limit setting was in force then.
So there are two tasks: find the first bad version in a history, and find the value that was in force at a given time.
A shop has a row of jars, from the oldest batch to the newest. One day the recipe went wrong, and every jar after that day is bad. A bad jar sometimes tastes fine on the first sip, so you take up to 5 sips of a jar.
One bitter sip is proof that a jar is bad. Five sweet sips are not proof, but they are enough. You taste the middle jar, and you keep the half that holds the first bad jar.
Here the sips are test runs, and the jars are versions.
Like tasting jars from oldest to newest: one bitter sip proves a jar is bad, and tasting the middle jar keeps the half with the first bad one.
Before you write code, bisect a small history by hand. It shows what one question costs.
Solve it by hand: Twelve versions, three runs each: find the first bad version. The hand-solve sheet loads in your browser.
The history has 12 versions, and each one has 3 runs. A failed run is F, and a passed run is P. You test the middle version, and you stop at the first failed run.
The runs are listed for every version, but you only look at the middle of the window.
| Step | Window | Middle | Runs of the middle | Runs used | Verdict |
|---|---|---|---|---|---|
| 1 | 0 to 12 | 6 | P, P, F | 3 | bad, so the window becomes 0 to 6 |
| 2 | 0 to 6 | 3 | P, P, P | 3 | good, so the window becomes 4 to 6 |
| 3 | 4 to 6 | 5 | P, P, P | 3 | good, so the window becomes 6 to 6 |
The window is empty at 6, so the first bad version is 6. You looked at 3 versions and ran 9 tests, and not 12 versions and up to 36 tests.
Start with a correct version. Run the versions in order, and stop at the first version that fails a run.
def first_bad_scan(runs):
for version in range(len(runs)):
for outcome in runs[version]: # up to 5 runs, stop at the first failure
if outcome == 1:
return version
return len(runs)This is correct. A good version always costs all its runs, and the scan reaches the first bad version after every good one before it.
Now check the real size.
The history has 100,000 versions, every version is run 5 times, and one run takes 6 minutes.
Here is the count:
So the scan could not finish before the next release, and the team asks it for every incident.
Predict the cost
Q A history has 100,000 versions, and the first bad one is at the end. Every good version is run 5 times, and one run takes 6 minutes. About how long does the scan take?
Answer: C
The count is 100,000 × 5 = 500,000 runs, and 500,000 × 6 = 3,000,000 minutes, which is about 5.7 years.
The first attempt is correct, but it never uses the order of the history. Now the team does.
Look at the hand trace again. The verdicts read good, good, good, good, good, good, bad, and then bad for ever. That is false and then true, the shape from the first lesson. The list is the history, and the check is "this version is bad".
The flaky test needs care. A test that fails at random cannot be trusted in both directions. So write the assumption down, as three exact statements.
With these three, one failed run is proof that a version is bad, and a version with no failed run is good. The check "at least one run failed" is then exact, and it flips once.
How many runs make the second statement true? Suppose each run of a bad version fails with probability p. The chance that all 5 runs pass is (1 - p)^5. Here is the chance for three values of p, with the number of runs that brings the chance to 1 percent or less, from a real run.
| Chance a run of a bad version fails | Chance all 5 runs pass | Runs for 1 percent or less |
|---|---|---|
| 0.3 | 0.168 | 13 |
| 0.5 | 0.031 | 7 |
| 0.9 | 0.00001 | 2 |
So with 5 runs, a test that fails 3 times in 10 misses a bad version about 1 time in 6. The number of runs is a decision you make from the failure rate, and you state it.
A good version never fails and a bad version fails a run, so one failed run is proof and a check can stop there.
Race: Run every version in order, against bisecting. The operation counter loads in your browser.
The race counts test runs. Every version needs up to 5 runs, and a bad version stops at its first failed run. The scan needs about 500,000 runs for 100,000 versions in the worst case measured. Bisecting needs 83.
The history has 15 versions with 3 runs each. The first 7 versions pass every run. The player runs the bisect. It stops at four steps and asks you to predict.
Dry run: Predict each step: fifteen versions, three runs each. The step-by-step player loads in your browser.
Reading without the player? Cover the last columns and predict them row by row.
| Step | Window | Middle | Runs of the middle | Runs used | Verdict |
|---|---|---|---|---|---|
| 1 | 0 to 15 | 7 | P, F, P | 2 | bad, so the window becomes 0 to 7 |
| 2 | 0 to 7 | 3 | P, P, P | 3 | good, so the window becomes 4 to 7 |
| 3 | 4 to 7 | 5 | P, P, P | 3 | good, so the window becomes 6 to 7 |
| 4 | 6 to 7 | 6 | P, P, P | 3 | good, so the window becomes 7 to 7 |
| end | 7 to 7 | the first bad version is 7 |
A version that fails stops at its first failed run, so a bad version costs fewer runs than a good one. Version 7 above used 2 runs, and the good versions used 3 each. The probes of good versions are the expensive ones, because a good verdict needs all the runs.
Here is the rule that keeps a search over a history correct.
Every version before lo is good and every version from hi on is bad or does not exist, so lo ends as the first bad version.
At the start, lo is 0 and no version is before it. And hi is the number of versions, which stands for "no bad version" and counts as bad. The rule holds.
If the middle version is bad, it and every later version are bad, so hi = mid keeps the rule. If it is good, it and every earlier version are good, so lo = mid + 1 keeps the rule. The window halves every step. When lo == hi, lo is the first bad version, and lo == n means that none is bad.
Use it when the versions are in order, a bad version stays bad, and you can test one version. Signal words: the first bad version, the first time a limit was passed, bisect.
Start: lo is 0. hi is the number of versions, or a version known to be bad.
Step: while lo < hi, set mid = lo + (hi - lo) / 2 and test version mid. If it is bad, set hi = mid. Otherwise set lo = mid + 1.
Stop: when lo == hi. The answer is lo. If lo is the number of versions, no version is bad.
It does not work when a bad version can become good again, or when a test result can be wrong in both directions.
Cost: log2 of the number of versions, plus 1, tests, each costing its repeated runs.
def first_bad(runs):
# [1] The window [lo, hi) holds the versions in question. hi = n stands for no bad version, and counts as bad.
lo = 0
hi = len(runs)
# [2] While the window holds a version, look at the version in its middle.
while lo < hi:
mid = (lo + hi) // 2
# [3] The check: run the version up to its repeats, and stop at the first failed run. One failed run is proof of a bad version.
failed = False
for outcome in runs[mid]:
if outcome == 1:
failed = True
break
if failed:
# [4] A bad version: so is every later version. It may be the first, so hi moves to it.
hi = mid
else:
# [5] A good version: so is every earlier version. lo moves past it.
lo = mid + 1
# [6] The window is empty: lo is the first bad version, or n when there is none.
return lopublic int firstBad(int[][] runs) {
// [1] The window [lo, hi) holds the versions in question. hi = n stands for no bad version, and counts as bad.
int lo = 0;
int hi = runs.length;
// [2] While the window holds a version, look at the version in its middle.
while (lo < hi) {
int mid = lo + (hi - lo) / 2;
// [3] The check: run the version up to its repeats, and stop at the first failed run. One failed run is proof of a bad version.
boolean failed = false;
for (int outcome : runs[mid]) {
if (outcome == 1) {
failed = true;
break;
}
}
if (failed) {
// [4] A bad version: so is every later version. It may be the first, so hi moves to it.
hi = mid;
} else {
// [5] A good version: so is every earlier version. lo moves past it.
lo = mid + 1;
}
}
// [6] The window is empty: lo is the first bad version, or n when there is none.
return lo;
}int firstBad(vector<vector<int>>& runs) {
// [1] The window [lo, hi) holds the versions in question. hi = n stands for no bad version, and counts as bad.
int lo = 0;
int hi = (int)runs.size();
// [2] While the window holds a version, look at the version in its middle.
while (lo < hi) {
int mid = lo + (hi - lo) / 2;
// [3] The check: run the version up to its repeats, and stop at the first failed run. One failed run is proof of a bad version.
bool failed = false;
for (int outcome : runs[mid]) {
if (outcome == 1) {
failed = true;
break;
}
}
if (failed) {
// [4] A bad version: so is every later version. It may be the first, so hi moves to it.
hi = mid;
} else {
// [5] A good version: so is every earlier version. lo moves past it.
lo = mid + 1;
}
}
// [6] The window is empty: lo is the first bad version, or n when there is none.
return lo;
}function firstBad(runs) {
// [1] The window [lo, hi) holds the versions in question. hi = n stands for no bad version, and counts as bad.
let lo = 0;
let hi = runs.length;
// [2] While the window holds a version, look at the version in its middle.
while (lo < hi) {
const mid = lo + Math.floor((hi - lo) / 2);
// [3] The check: run the version up to its repeats, and stop at the first failed run. One failed run is proof of a bad version.
let failed = false;
for (const outcome of runs[mid]) {
if (outcome === 1) {
failed = true;
break;
}
}
if (failed) {
// [4] A bad version: so is every later version. It may be the first, so hi moves to it.
hi = mid;
} else {
// [5] A good version: so is every earlier version. lo moves past it.
lo = mid + 1;
}
}
// [6] The window is empty: lo is the first bad version, or n when there is none.
return lo;
}Rebuild the template: put its lines back in order. Loads in your browser.
Exercise · Predict the output: How many runs does the bisect read?. Seven versions with three runs each, where 1 is a failed run. The bisect stops reading a version at its first failed run. What does it print: the first bad version, then the runs read?
runs = [[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 1, 0], [1, 0, 0], [0, 0, 1], [1, 1, 1]]
lo, hi = 0, len(runs)
read = 0
while lo < hi:
mid = (lo + hi) // 2
failed = False
for outcome in runs[mid]:
read += 1
if outcome == 1:
failed = True
break
if failed:
hi = mid
else:
lo = mid + 1
print(lo, read)Exercise · Find the bug: The failed run that gets overwritten. This bisect should call a version bad when any of its runs fails. It misses some bad versions. Which line is wrong?
def first_bad(runs):
lo, hi = 0, len(runs)
while lo < hi:
mid = lo + (hi - lo) // 2
failed = False
for outcome in runs[mid]:
failed = outcome == 1
if failed:
hi = mid
else:
lo = mid + 1
return loNow the second task. Changes to a setting are stored with the time they were made, in increasing order of time. The question is: which value was in force at time t?
The answer is the last change made at or before t. The changes are sorted by time, so the first change after t can be found with the same search. The change before it is the answer. This is the upper bound, minus one.
def value_at(times, values, t):
# [1] The window [lo, hi) holds the changes in question. hi = n stands for no change after the time.
lo = 0
hi = len(times)
# [2] While the window holds a change, look at the change in its middle.
while lo < hi:
mid = (lo + hi) // 2
if times[mid] <= t:
# [3] The change is at or before the time, and so is every earlier change. lo moves past it.
lo = mid + 1
else:
# [4] The change is after the time, and so is every later change. It may be the first, so hi moves to it.
hi = mid
# [5] lo is the first change after the time. The change before it was in force. With no such change, the answer is -1.
return values[lo - 1] if lo > 0 else -1public int valueAt(int[] times, int[] values, long t) {
// [1] The window [lo, hi) holds the changes in question. hi = n stands for no change after the time.
int lo = 0;
int hi = times.length;
// [2] While the window holds a change, look at the change in its middle.
while (lo < hi) {
int mid = lo + (hi - lo) / 2;
if (times[mid] <= t) {
// [3] The change is at or before the time, and so is every earlier change. lo moves past it.
lo = mid + 1;
} else {
// [4] The change is after the time, and so is every later change. It may be the first, so hi moves to it.
hi = mid;
}
}
// [5] lo is the first change after the time. The change before it was in force. With no such change, the answer is -1.
return lo > 0 ? values[lo - 1] : -1;
}int valueAt(vector<int>& times, vector<int>& values, long long t) {
// [1] The window [lo, hi) holds the changes in question. hi = n stands for no change after the time.
int lo = 0;
int hi = (int)times.size();
// [2] While the window holds a change, look at the change in its middle.
while (lo < hi) {
int mid = lo + (hi - lo) / 2;
if (times[mid] <= t) {
// [3] The change is at or before the time, and so is every earlier change. lo moves past it.
lo = mid + 1;
} else {
// [4] The change is after the time, and so is every later change. It may be the first, so hi moves to it.
hi = mid;
}
}
// [5] lo is the first change after the time. The change before it was in force. With no such change, the answer is -1.
return lo > 0 ? values[lo - 1] : -1;
}function valueAt(times, values, t) {
// [1] The window [lo, hi) holds the changes in question. hi = n stands for no change after the time.
let lo = 0;
let hi = times.length;
// [2] While the window holds a change, look at the change in its middle.
while (lo < hi) {
const mid = lo + Math.floor((hi - lo) / 2);
if (times[mid] <= t) {
// [3] The change is at or before the time, and so is every earlier change. lo moves past it.
lo = mid + 1;
} else {
// [4] The change is after the time, and so is every later change. It may be the first, so hi moves to it.
hi = mid;
}
}
// [5] lo is the first change after the time. The change before it was in force. With no such change, the answer is -1.
return lo > 0 ? values[lo - 1] : -1;
}To find the value in force at a time, find the first change after the time with a search, and take the change right before it.
Dry run: Predict each step: the value at time 17. The step-by-step player loads in your browser.
The player looks up the time 17 in a history of 5 changes. The times are 3, 10, 18, 25 and 40, and the values are 100, 120, 90, 130 and 110. It stops at the first step and asks you to predict.
Exercise · Put it in order: The value in force at a time. Arrange the lines into a function that returns the value set by the last change at or before time t, or -1 when no change has happened yet.
def value_at(times, values, t):
lo = 0
hi = len(times)
while lo < hi:
mid = lo + (hi - lo) // 2
if times[mid] <= t:
lo = mid + 1
else:
hi = mid
return values[lo - 1] if lo > 0 else -1
return values[lo]For every search over a history, write down three things: the check, why it flips once, and what the end of the window means.
| Problem | The check on an entry | Why it flips once | What hi == n means |
|---|---|---|---|
| First bad version | At least one run failed | A bad version stays bad, and a bad version fails a run | No version is bad |
| Value at a time | This change is after the time | Changes are sorted by time, so later changes are later too | No change is after the time, so the last change is the answer |
| First day over a limit | The daily rate is above the limit | The rate never falls | No day is over the limit |
The audit team asks for the daily payment limit in force at certain times. The limit was set at the times 3, 10, 18, 25 and 40, to the values 100, 120, 90, 130 and 110.
For time 17 the search looks at entry 2 (time 18, after 17), then at entry 1 (time 10, not after 17). The window ends at 2, the first change after 17, so the answer is the value of entry 1: 120.
For time 18 the answer is 90, because a change at exactly 18 counts. For time 2 the window ends at 0, and the answer is -1.
A time in seconds can be as large as 10^9, which fits in a 32-bit integer, but a time in milliseconds does not. The template takes t as a 64-bit number, so a question can be larger than any stored time.
The search itself never adds two large numbers. The middle is lo + (hi - lo) / 2, and lo and hi are positions in the list.
Real production data brings edge cases.
For runs = [[0, 0], [0, 0]], no run failed. Every middle is good, lo moves to 2, and the template returns 2, the number of versions. That means "no bad version".
For runs = [[0, 1], [1, 1]], the first version fails a run. The middle (version 1) is bad, so hi moves to 1, and then the middle (version 0) is bad too. The answer is 0.
For times = [3, 10, 18, 25, 40] and t = 2, every change is after the time. The window ends at 0, and the answer is -1, because nothing was set yet.
For the same history and t = 18, the change at time 18 counts: it is at or before the time. The answer is 90, not the earlier 120.
This version tests each version once, with its first run. A bad version that passes its first run looks good.
Counterexample: the twelve versions of the hand trace. The first bad version is 6, which fails only on its third run.
Testing the first run only, the bisect returns 9. Several bad versions pass their first run.
Testing only the first run of each version calls a bad version good when it passes that run, so the bisect returns version 9 and not 6.
This version calls a version bad when more than half of its runs failed. A bad version that fails one run in three looks good.
Counterexample: the same twelve versions. Version 6 fails 1 run of 3, so the majority rule calls it good, and the bisect returns 9, not 6.
This version of the time lookup moves lo only when times[mid] < t. A change made exactly at the time is then treated as later.
Counterexample: times = [3, 10, 18, 25, 40], values = [100, 120, 90, 130, 110] and t = 18. The version returns 120, but the change at 18 is in force, so the answer is 90. For t = 3 it returns -1 instead of 100.
This version returns values[lo - 1] without checking that lo is above 0. In Python, position -1 is the last entry.
Counterexample: the same history and t = 2. The version returns 110, the last value, instead of -1.
Exercise · Break it: Find the time this lookup gets wrong. This function returns the value in force at time t. It reads the change before the first later change, with no check on the position. Find an input where it gives the wrong answer.
def value_at(times, values, t):
lo, hi = 0, len(times)
while lo < hi:
mid = lo + (hi - lo) // 2
if times[mid] <= t:
lo = mid + 1
else:
hi = mid
return values[lo - 1]Suppose a bug is fixed in version 3, so the versions read good, bad, bad, good, good, good, good, good. The check is false, true, true, false: it does not flip once.
For runs = [[0, 0], [1, 1], [1, 0], [0, 0], [0, 0], [0, 0], [0, 0], [0, 0]], the first bad version is 1.
The bisect looks at version 4, which is good, and moves lo up. It ends at 8, which means "no bad version". The answer 1 is lost.
Your team lead brings four product changes. Each one asks what the order is, and what the check is.
A single history with a stored flag for every version is the plain bisect. The check is a call that says good or bad (LeetCode 278: First Bad Version).
A store keeps values with timestamps for many keys. Each key has its own sorted list of times, and a question is the upper bound, minus one (LeetCode 981: Time Based Key-Value Store).
Settings are copied only when they change, and a snapshot number plays the part of a time. The answer is the last change at or before the snapshot (LeetCode 1146: Snapshot Array).
A daily rate never falls, and the limit is a fraction. The check compares the fractions by cross-multiplying, with 64-bit numbers, and the search finds the first day over the limit.
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 bad version when the test is flaky. Then explain how you find the value that was in force at a past time. 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 bisect the history. I test the middle version, and I keep the half that holds the first bad one.
The test is flaky, so I state the assumption: a good version never fails, and a bad version fails at least one run. Then one failed run is proof, and I stop at the first failure.
For the value at a time, I find the first change after the time, with an upper bound, and I take the change before it.
A history is ordered, so I do not test every version. I write the check for one version and I prove that a bad version stays bad. Then I bisect: test the middle, and keep the half that holds the first bad one.
With a flaky test, I state the assumption exactly. A good version never fails. A bad version fails at least one of its runs. Then one failed run is proof, so I stop at the first failure, and I choose the number of runs from the failure rate.
For a question about the past, such as the value at a time, I search the sorted changes for the first change after the time. The change before it is the answer, and I return a default when there is none.
The cost is the number of tests, log of the history, times the runs of one test.
Checkpoint · Bisect and lookups
Q1/10 A history has versions in release order, and once a version is bad every later one is bad. What do the verdicts of a test read as the version number grows?
Answer: B
A bad version stays bad, so the verdicts are false and then true for ever. That is the shape that the first-true template needs.
Q2/10 A bad version may pass its first run. Which check is exact when a good version never fails and a bad version fails at least one run?
Answer: C
One failed run is proof of a bad version, and a version with no failed run is good. The first run alone, or a majority, can call a bad version good.
Q3/10 Which statement must you be able to make before you bisect with a flaky test?
Answer: B
Without these two statements a failed run is not proof, or a pass is not good, and the check is not exact. The third assumption is that a bad version stays bad.
Q4/10 Each run of a bad version fails with probability 0.3. How likely is it that all 5 runs pass, so the bad version looks good?
Answer: C
All 5 runs pass with probability 0.7 to the power 5, which is 0.168. Choosing the number of runs from the failure rate keeps that chance small.
Q5/10 A history of changes is sorted by time, and you want the value in force at time t. What do you search for?
Answer: B
The last change at or before t is the one before the first change after t. That is the upper bound, minus one.
Q6/10 The times of the changes are 3, 10, 18, 25 and 40, and you ask for the value at time 18. Which comparison treats the change at time 18 correctly?
Answer: B
A change made exactly at the time is in force at that time, so it must count as not later. The strict comparison returns the earlier value.
Q7/10 The same changes, and you ask for the value at time 2. What does the search return, and why?
Answer: B
Every change is after time 2, so lo stays at 0. There is no change before position 0, so the answer is the default, -1.
Q8/10 In Python, the search ends with lo equal to 0 and the code returns values[lo - 1] without a check. What does it return?
Answer: C
Python counts negative positions from the end, so values[-1] is the last entry. Check that lo is above 0 first.
Q9/10 A history has 100,000 versions and every version is run up to 5 times. At most how many runs does the bisect need?
Answer: C
The window halves each step, so there are at most 17 tests for 100,000 versions. Each test uses up to 5 runs, which makes 85.
Q10/10 A bug is fixed in a later version, so the versions read good, bad, bad, good, good. Why does a bisect fail?
Answer: C
The template needs a bad version to stay bad. With a fix in between, the search can move into the fixed part and lose the first bad version.
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 | First bad commit with flaky tests | Platform | Medium | A bisect where one failed run is proof |
| 2 | Bisect over a monotone health check | Streaming | Medium | An or of two monotone checks as one check |
| 3 | Settings at a past snapshot | Chat | Medium | The upper bound, minus one, over stored changes |
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.