Search over real numbers to a precision, and over sorted matrices.
Use it when the answer is a real number, and you can test one candidate. A larger candidate must never hurt, or a smaller one must never hurt. Signal words: the lowest rate, the length to six places, the root.
Start lo is a value that cannot be the answer, or the smallest allowed value. hi is a value that surely passes the check.
Step repeat 100 times. Set mid = (lo + hi) / 2 and run the check on mid. If it passes, set hi = mid. Otherwise set lo = mid.
Stop after the rounds. Scale the answer to the precision that the problem asks for, and round in the direction that the problem needs.
It does not work when the check passes, fails and passes again. And it cannot give an exact answer, only one inside the precision that doubles hold.
Cost: rounds × the cost of one check. For 100 rounds and a check of O(months), that is O(100 × months).
In this lesson the answer is a real number, or it hides in a table. You search a range of real numbers for a fixed number of rounds, and you walk a sorted table from a corner. Both ideas come from the first-true template.
You work on the savings feature of a bank app. A member pays 100 units into a plan at the end of each month, for 36 months. The bank adds interest to the balance every month at one fixed monthly rate. The member wants 4,500 units at the end.
Your team lead says: Show the member the lowest monthly rate that reaches the target. Give it in millionths of a rate, rounded up, so that the plan never promises too little.
The plans offer rates up to 0.05 a month, which is 5 percent. A plan can last up to 480 months. The app builds a table of 10,000 plans every night.
So the task is this: find the lowest rate that reaches the target, when a rate is a real number and not a whole number.
You turn a tap to get water at a comfortable heat. There is no list of tap positions. You turn it halfway between "too cold" and "too hot", feel the water, and choose the half that still holds the right heat.
After a few turns the two ends are so close that you cannot feel a difference. You stop because the answer is accurate enough, not because you found an exact position.
Here the water is a check. You try one rate, and the check says "too low" or "reaches the target".
Like tuning a tap: there is no list of positions, and each feel of the water tells you which half still holds the answer.
Before you write code, halve the range of rates by hand. It shows what one question costs.
Solve it by hand: 100 units a month for 36 months: the lowest rate that reaches 4,500. The hand-solve sheet loads in your browser.
You start with the rates between 0 and 0.05. For each middle rate you grow the balance month by month, and you keep the half that still holds the answer.
Plan: 100 units a month, 36 months, target 4,500. The range starts as 0 to 0.05.
| Round | Range before | Middle rate | Balance after 36 months | Target reached? |
|---|---|---|---|---|
| 1 | 0 to 0.05 | 0.025 | 5,730.1413 | yes, so the upper end moves to 0.025 |
| 2 | 0 to 0.025 | 0.0125 | 4,511.5505 | yes, so the upper end moves to 0.0125 |
| 3 | 0 to 0.0125 | 0.00625 | 4,023.1382 | no, so the lower end moves to 0.00625 |
| 4 | 0.00625 to 0.0125 | 0.009375 | 4,258.5384 | no, so the lower end moves to 0.009375 |
| 5 | 0.009375 to 0.0125 | 0.0109375 | 4,382.7564 | no, so the lower end moves to 0.0109375 |
| 6 | 0.0109375 to 0.0125 | 0.01171875 | 4,446.5702 | no, so the lower end moves to 0.01171875 |
Each round halves the range. After six rounds the range is 0.01171875 to 0.0125, and the answer is somewhere inside it.
Start with a correct version. Try the rates one millionth apart, from 0, and stop at the first one that reaches the target.
def needed_rate_scan(deposit, months, target):
millionths = 0
while True:
rate = millionths / 1000000
balance = 0.0
for _ in range(months): # one pass over the months
balance = balance * (1 + rate) + deposit
if balance >= target:
return millionths
millionths += 1This is correct. One try grows the balance through every month, and the number of tries is the answer itself, counted in millionths.
Now check the real size.
A plan can last 480 months, a rate can be as high as 50,000 millionths, and the app builds 10,000 plans a night.
Here is the count:
So the nightly table would take most of an hour, and a member who changes a target waits for a full scan.
Predict the cost
Q A plan lasts 480 months, the answer can be as high as 50,000 millionths, and the first attempt tries every millionth from 0. About how many steps does one plan cost, in the worst case?
Answer: C
The count is 50,000 tries × 480 months = 24,000,000 steps for one plan. For 10,000 plans that is 2.4 × 10^11.
The first attempt is correct, but it never uses what the table showed. Now the team does.
Look at the hand trace again. The balance only went down when the rate went down: 5,730, 4,512, 4,023. The answers to "reaches 4,500?" read yes for the rates 0.025 and 0.0125, and no for the lower rates.
That is false and then true, the shape from the first lesson. The difference is that the candidates are real numbers, so the line of candidates has no "next" one and no last position.
Why does the check flip only once? The balance after month k is built from the month before: balance = balance × (1 + rate) + deposit. A higher rate gives a higher growth factor, and the balance is never negative. By induction, every month's balance can only go up when the rate goes up.
So you run the first-true template on the rates. Two things change for real numbers.
mid + 1. A rate a little above mid is not mid + 1, so when the check fails the lower end moves to mid itself.lo == hi. You stop after a fixed number of rounds, or when the range is narrow enough.Each round tests the middle rate and keeps one half, so the range of rates halves until the ends are neighbouring doubles.
Each round halves the range, so after k rounds the range is 0.05 / 2^k wide. Here is the width for the plan above, from a real run, with the answer that lo gives after that many rounds.
| Rounds | Width of the range | Answer from lo, rounded up |
|---|---|---|
| 10 | 4.9 × 10^-5 | 12354 |
| 16 | 7.6 × 10^-7 | 12362 |
| 20 | 4.8 × 10^-8 | 12363 |
| 30 | 4.7 × 10^-11 | 12363 |
| 40 | 4.5 × 10^-14 | 12363 |
| 60 | 1.7 × 10^-18 | 12363 |
| 100 | 1.7 × 10^-18 | 12363 |
Two facts matter.
First, a range narrower than a millionth is not accurate enough for six places. After 16 rounds the width is below 10^-6, and the answer is 12362, which is one too low. Second, the width stops shrinking at 1.7 × 10^-18, because that is the gap between neighbouring doubles near this rate. In the run, the middle of the range equals one of its ends from round 56 on.
A fixed count of 100 rounds divides the width by 2^100, about 10^30. Here that is far more than doubles can use, and even a range of 10^18 would end below 10^-12. The loop cannot run for ever.
Race: Try every millionth, against halving. The operation counter loads in your browser.
The race counts rates tried. A range of 0.001 holds 1,000 millionths, and the first attempt tries up to 1,000 of them. Halving needs 10 rounds.
A range of 1 holds 1,000,000 millionths, and halving needs 20. The template uses 100 rounds every time, which still beats the scan from a range of 1,000 millionths.
The plan is 250 units a month for 24 months, with a target of 6,200 units. The player runs the search over the rates 0 to 0.05. It stops at five steps and asks you to predict.
Dry run: Predict each step: 250 units a month for 24 months and a target of 6,200. The step-by-step player loads in your browser.
Reading without the player? Cover the last columns and predict them row by row.
| Round | Range before | Middle rate | Balance after 24 months | What moves |
|---|---|---|---|---|
| 1 | 0 to 0.05 | 0.025 | 8,087.2595 | reached, so the upper end moves to 0.025 |
| 2 | 0 to 0.025 | 0.0125 | 6,947.021 | reached, so the upper end moves to 0.0125 |
| 3 | 0 to 0.0125 | 0.00625 | 6,451.6807 | reached, so the upper end moves to 0.00625 |
| 4 | 0 to 0.00625 | 0.003125 | 6,220.6485 | reached, so the upper end moves to 0.003125 |
| 5 | 0 to 0.003125 | 0.0015625 | 6,109.058 | not reached, so the lower end moves to 0.0015625 |
| 100 | both ends 0.002838571813 | the answer is 2838.571813 millionths, rounded up to 2839 |
At the end the range holds the answer, and lo is a hair below it. The member needs a rate that surely reaches the target, so you round up to a whole millionth.
For the first plan, lo is 0.012362160234, which is 12362.160234 millionths. Rounding up gives 12363. At 12362 millionths the balance is 4,499.9866, below the target. At 12363 it is 4,500.0703.
Here is the rule that keeps a search over real numbers correct.
Every rate below lo fails the check and every rate above hi passes it, so the lowest rate that passes always lies between lo and hi.
At the start, lo is 0 and no rate below it is allowed. And hi is a rate that is known to pass, so every higher rate passes too, because the check is monotone. The rule holds.
If the check fails at mid, every rate up to mid fails too, so lo = mid keeps the rule. If it passes, every rate above mid passes too, so hi = mid keeps the rule. The range halves every round, so after k rounds it is 1 / 2^k of its first width.
Use it when the answer is a real number, and you can test one candidate. A larger candidate must never hurt, or a smaller one must never hurt. Signal words: the lowest rate, the length to six places, the root.
Start: lo is a value that cannot be the answer, or the smallest allowed value. hi is a value that surely passes the check.
Step: repeat 100 times. Set mid = (lo + hi) / 2 and run the check on mid. If it passes, set hi = mid. Otherwise set lo = mid.
Stop: after the rounds. Scale the answer to the precision that the problem asks for, and round in the direction that the problem needs.
It does not work when the check passes, fails and passes again. And it cannot give an exact answer, only one inside the precision that doubles hold.
Cost: rounds × the cost of one check. For 100 rounds and a check of O(months), that is O(100 × months).
import math
def needed_rate(deposit, months, target):
# [1] The rate lies between 0 and 0.05 a month. The plans offer at most 5 percent a month, and the target is within reach at that rate, so hi works.
lo = 0.0
hi = 0.05
# [2] Halve the interval a fixed 100 times. That is far more than doubles can use, and it needs no tolerance.
for _ in range(100):
mid = (lo + hi) / 2
# [3] The check for this one rate: grow a balance month by month, interest on the balance first and then the deposit.
balance = 0.0
for _ in range(months):
balance = balance * (1 + mid) + deposit
if balance >= target:
# [4] The rate works, so every higher rate works too. It may be the lowest, so keep it: hi moves to it.
hi = mid
else:
# [5] The rate is too low, so every lower rate is too. lo moves to it: rates are not whole numbers, so there is no + 1.
lo = mid
# [6] lo is just below the lowest working rate. Round it up to a whole millionth, the first rate that surely works.
return math.ceil(lo * 1000000)public long neededRate(int deposit, int months, long target) {
// [1] The rate lies between 0 and 0.05 a month. The plans offer at most 5 percent a month, and the target is within reach at that rate, so hi works.
double lo = 0.0;
double hi = 0.05;
// [2] Halve the interval a fixed 100 times. That is far more than doubles can use, and it needs no tolerance.
for (int round = 0; round < 100; round++) {
double mid = (lo + hi) / 2;
// [3] The check for this one rate: grow a balance month by month, interest on the balance first and then the deposit.
double balance = 0.0;
for (int month = 0; month < months; month++) {
balance = balance * (1 + mid) + deposit;
}
if (balance >= target) {
// [4] The rate works, so every higher rate works too. It may be the lowest, so keep it: hi moves to it.
hi = mid;
} else {
// [5] The rate is too low, so every lower rate is too. lo moves to it: rates are not whole numbers, so there is no + 1.
lo = mid;
}
}
// [6] lo is just below the lowest working rate. Round it up to a whole millionth, the first rate that surely works.
return (long) Math.ceil(lo * 1000000);
}long long neededRate(int deposit, int months, long long target) {
// [1] The rate lies between 0 and 0.05 a month. The plans offer at most 5 percent a month, and the target is within reach at that rate, so hi works.
double lo = 0.0;
double hi = 0.05;
// [2] Halve the interval a fixed 100 times. That is far more than doubles can use, and it needs no tolerance.
for (int round = 0; round < 100; round++) {
double mid = (lo + hi) / 2;
// [3] The check for this one rate: grow a balance month by month, interest on the balance first and then the deposit.
double balance = 0.0;
for (int month = 0; month < months; month++) {
balance = balance * (1 + mid) + deposit;
}
if (balance >= (double)target) {
// [4] The rate works, so every higher rate works too. It may be the lowest, so keep it: hi moves to it.
hi = mid;
} else {
// [5] The rate is too low, so every lower rate is too. lo moves to it: rates are not whole numbers, so there is no + 1.
lo = mid;
}
}
// [6] lo is just below the lowest working rate. Round it up to a whole millionth, the first rate that surely works.
return (long long)ceil(lo * 1000000);
}function neededRate(deposit, months, target) {
// [1] The rate lies between 0 and 0.05 a month. The plans offer at most 5 percent a month, and the target is within reach at that rate, so hi works.
let lo = 0.0;
let hi = 0.05;
// [2] Halve the interval a fixed 100 times. That is far more than doubles can use, and it needs no tolerance.
for (let round = 0; round < 100; round++) {
const mid = (lo + hi) / 2;
// [3] The check for this one rate: grow a balance month by month, interest on the balance first and then the deposit.
let balance = 0.0;
for (let month = 0; month < months; month++) {
balance = balance * (1 + mid) + deposit;
}
if (balance >= target) {
// [4] The rate works, so every higher rate works too. It may be the lowest, so keep it: hi moves to it.
hi = mid;
} else {
// [5] The rate is too low, so every lower rate is too. lo moves to it: rates are not whole numbers, so there is no + 1.
lo = mid;
}
}
// [6] lo is just below the lowest working rate. Round it up to a whole millionth, the first rate that surely works.
return Math.ceil(lo * 1000000);
}Rebuild the template: put its lines back in order. Loads in your browser.
For every real-valued problem, write down four things: the check, why it is monotone, the range, and how the answer is rounded.
| Problem | The check on a candidate | Why it flips once | lo and hi | Rounding |
|---|---|---|---|---|
| Lowest rate for a savings goal | The balance after the last month is at least the target | A higher rate never gives a lower balance | lo = 0. hi = 0.05, where the target is within reach | Up, to a whole millionth |
Square root of a, for a of at least 1 |
x × x is at least a |
Squares grow as x grows from 0 |
lo = 0. hi = a, because a is at least its own root |
Down, to a whole millionth |
| The k-th smallest entry of a sorted grid | At least k entries are at most this value |
A larger value never counts fewer entries | lo = the first entry. hi = the last entry | None: the candidates are whole values |
The last row is not real-valued. It shows that the check from this lesson, a count, is the same idea: a monotone check that you can run on any candidate.
A tile maker needs a square tile with an area of 10 square units, and the side to six places. The check on a side x is that x × x is at least 10. The range is lo = 0 to hi = 10.
After 100 rounds, lo is 3.162277660168379 and hi is 3.1622776601683795. In millionths, lo is 3162277.66, and the problem rounds down: 3162277.
Only the check, the range and the rounding changed. The 100 rounds did not change.
Exercise · Put it in order: The whole-number square root. Arrange the lines into a function that returns the largest whole number whose square is at most a. The candidates are whole numbers, so there are no rounds.
def int_sqrt(a):
lo = 0
hi = a + 1
while lo < hi:
mid = lo + (hi - lo) // 2
if mid * mid <= a:
lo = mid + 1
else:
hi = mid
return lo - 1
return loDoubles hold about 15 to 16 significant digits. A rate of 0.0124 can be told apart from its neighbours down to 10^-18, and a side of 1,000 down to about 10^-13. Both are far below a millionth, so six places are safe.
The final conversion matters more than the rounds. A value that sits a hair below an exact answer rounds down to the wrong whole number, as the first mistake in the museum shows.
Now the second half of the lesson. A grid is sorted along its rows and along its columns. Every row grows to the right, and every column grows downwards, but one row can run past the start of the next.
Look at one corner. In the top-right corner the row can only get smaller to the left, and the column can only get larger downwards. That gives a decision at every entry.
Every step removes a row or a column, so the walk takes at most m + n - 1 steps for a grid of m rows and n columns.
def count_at_most(grid, limit):
m = len(grid)
n = len(grid[0])
# [1] Start in the top-right corner. There the row grows to the left and the column grows downwards.
row = 0
col = n - 1
count = 0
# [2] While the corner is still inside the grid, look at its entry.
while row < m and col >= 0:
if grid[row][col] <= limit:
# [3] The entry fits, so everything to its left in this row fits too. Add them all, and go down a row.
count += col + 1
row += 1
else:
# [4] The entry is too big, so everything below it in this column is too big. Go left a column.
col -= 1
# [5] The corner has left the grid: every entry at most the limit has been counted.
return countpublic long countAtMost(int[][] grid, int limit) {
int m = grid.length;
int n = grid[0].length;
// [1] Start in the top-right corner. There the row grows to the left and the column grows downwards.
int row = 0;
int col = n - 1;
long count = 0;
// [2] While the corner is still inside the grid, look at its entry.
while (row < m && col >= 0) {
if (grid[row][col] <= limit) {
// [3] The entry fits, so everything to its left in this row fits too. Add them all, and go down a row.
count += col + 1;
row++;
} else {
// [4] The entry is too big, so everything below it in this column is too big. Go left a column.
col--;
}
}
// [5] The corner has left the grid: every entry at most the limit has been counted.
return count;
}long long countAtMost(vector<vector<int>>& grid, int limit) {
int m = (int)grid.size();
int n = (int)grid[0].size();
// [1] Start in the top-right corner. There the row grows to the left and the column grows downwards.
int row = 0;
int col = n - 1;
long long count = 0;
// [2] While the corner is still inside the grid, look at its entry.
while (row < m && col >= 0) {
if (grid[row][col] <= limit) {
// [3] The entry fits, so everything to its left in this row fits too. Add them all, and go down a row.
count += col + 1;
row++;
} else {
// [4] The entry is too big, so everything below it in this column is too big. Go left a column.
col--;
}
}
// [5] The corner has left the grid: every entry at most the limit has been counted.
return count;
}function countAtMost(grid, limit) {
const m = grid.length;
const n = grid[0].length;
// [1] Start in the top-right corner. There the row grows to the left and the column grows downwards.
let row = 0;
let col = n - 1;
let count = 0;
// [2] While the corner is still inside the grid, look at its entry.
while (row < m && col >= 0) {
if (grid[row][col] <= limit) {
// [3] The entry fits, so everything to its left in this row fits too. Add them all, and go down a row.
count += col + 1;
row++;
} else {
// [4] The entry is too big, so everything below it in this column is too big. Go left a column.
col--;
}
}
// [5] The corner has left the grid: every entry at most the limit has been counted.
return count;
}From the top-right corner, a fitting entry counts its whole row prefix and moves down, and a big entry drops its whole column.
Dry run: Predict each step: how many entries are at most 8?. The step-by-step player loads in your browser.
The player counts the entries at most 8 in the 4 × 4 grid of the template example. It stops at four steps and asks you to predict.
A parcel app has a fee table. The rows are weight bands and the columns are distance bands, and the fee grows along both. The grid is [[1, 4, 7, 11], [2, 5, 8, 12], [3, 6, 9, 16], [10, 13, 14, 17]], and the limit is 8.
The walk starts at the top-right entry, 11, and takes 7 steps. It adds 3 entries in row 0, 3 in row 1, and 2 in row 2, and it ends with a count of 8. Reading all 16 entries gives the same count.
The same walk answers "does the value v appear?". Stop when the entry equals v, go left when it is larger, and go down when it is smaller.
Here is the cost of three ways to look for a value in a grid of n rows and n columns, whose entries are 3r + 5c. Each number is the worst case over every value from -1 up to the largest entry plus 1, from a real run.
| Grid | Read every entry | Binary search in each row | Staircase |
|---|---|---|---|
| 10 × 10 | 100 | 40 | 14 |
| 100 × 100 | 10,000 | 700 | 104 |
| 1000 × 1000 | 1,000,000 | 10,000 | 1,004 |
When the rows continue one another, as pages of one list, read the grid as one sorted list and run one binary search. The practice problem about pages does this. When they do not continue, the staircase is the tool, and the flat search gives wrong answers.
Use it when every row and every column is sorted, but the rows overlap. Signal words: sorted by rows and by columns, a table that grows both ways.
Start: the top-right corner (or the bottom-left corner, by symmetry).
Step: compare the corner entry with the target. If it is too small for the question, move down. If it is too large, move left. Each step discards a whole row or a whole column.
Stop: when the corner leaves the grid, or when the entry matches.
It does not work when only the rows are sorted, or from the top-left corner, where both directions grow and no decision discards a line.
Cost: at most m + n - 1 steps, and O(1) extra space.
Exercise · Predict the output: Where does the staircase walk end?. A grid grows along its rows and down its columns. This walk starts in the top-right corner and counts the entries at most 6. What does it print: the count, then the number of steps?
grid = [[1, 3, 5], [2, 6, 9], [4, 7, 10]]
limit = 6
row, col = 0, len(grid[0]) - 1
count = 0
steps = 0
while row < len(grid) and col >= 0:
steps += 1
if grid[row][col] <= limit:
count += col + 1
row += 1
else:
col -= 1
print(count, steps)Exercise · Find the bug: The row that is counted one short. This staircase walk counts the entries at most a limit in a grid sorted along its rows and down its columns. It counts too few. Which line is wrong?
def count_at_most(grid, limit):
row, col = 0, len(grid[0]) - 1
count = 0
while row < len(grid) and col >= 0:
if grid[row][col] <= limit:
count += col
row += 1
else:
col -= 1
return countm + n - 1 steps. For a grid of 1,000 × 1,000 that is at most 1,999 steps, against 1,000,000 entries.3r + 5c. Its 250,000th smallest entry needs 13 checks of at most 1,999 steps, found by searching the answer values.Real production data brings edge cases.
For deposit = 100, months = 36 and target = 3600, the deposits alone reach the target, so the rate 0 works. Every middle rate passes, hi shrinks to 3.9 × 10^-32, and lo stays at 0. The answer is 0.
For deposit = 1000, months = 1 and target = 1000, the balance is 1000 at every rate, because interest never has time to act. The rate 0 works, so the answer is 0.
For grid = [[1, 4, 7, 11], [2, 5, 8, 12], [3, 6, 9, 16], [10, 13, 14, 17]] and limit = 0, every entry is above the limit. The walk goes left four times, takes 4 steps and returns 0.
For grid = [[1, 2, 3, 4]] and limit = 2, the walk goes left from column 3 to column 1 and adds 2. Then it goes down and leaves the grid. The count is 2.
This version loops while hi - lo > 0.000001, because the answer is wanted to a millionth. It returns after 16 rounds, when lo is 12361.9 millionths.
Counterexample: deposit = 100, months = 36 and target = 4500. The version returns 12362, but at 12362 millionths the balance is 4,499.9866. The correct answer is 12363. A range that is one millionth wide cannot give the sixth place after rounding up.
Stopping when the range is one millionth wide returns 12362, one too low, because that range cannot fix the sixth place.
This version loops while hi - lo > 1e-18. Near the rate 0.0124, neighbouring doubles are 1.7 × 10^-18 apart, so hi - lo can never get below that gap.
Counterexample: deposit = 100, months = 36 and target = 4500. After 10,000 rounds the width is still 1.7 × 10^-18, and the loop never ends. A fixed count of rounds always ends.
This version copies the integer template and sets lo = mid + 1 when the check fails. For a real rate, adding 1 jumps past the whole range.
Counterexample: deposit = 100, months = 36 and target = 4500. After the first fail, at round 3, lo is 1.00625. The version returns 1006251 millionths, a rate above 1, when the correct answer is 12363.
This version rounds up hi and not lo. The value hi never equals 0, because it is always a middle point above lo.
Counterexample: deposit = 100, months = 36 and target = 3600. The deposits alone reach the target, so the answer is 0. But hi ends at 3.9 × 10^-32, and rounding it up gives 1.
This version reads the grid in reading order and runs one binary search. That is valid only when each row starts above the end of the row before it.
Counterexample: grid = [[1, 4, 7], [2, 5, 8], [3, 6, 9]] and the value 2. The reading order is 1, 4, 7, 2, 5, 8, 3, 6, 9, which is not sorted. The flat search reports 2 as missing, but it sits at row 1, column 0.
Your team lead asks for a rate whose balance is within 1 unit of 4,500, and not at least 4,500. The balance is in that band only for the rates 12351 to 12374 millionths. Everywhere else the check is false.
The check is false, then true for 24 millionths, then false again. The search checks the rate 0.025, which fails, so lo moves up. It ends at 0.05, and the answer is 50000, which is far outside the band. Ask for "at least 4,500" and the search finds 12363.
Your team lead brings four product changes. Each one asks what the candidates are, and what the check is.
A payments chart needs the largest whole number whose square fits an amount. The candidates are whole numbers, so the integer template applies, with no rounds and no rounding (LeetCode 69: Sqrt(x)).
A statement is a grid of pages, and each page continues the one before. The grid reads as one sorted list, and one binary search finds a number (LeetCode 74: Search a 2D Matrix).
A search engine keeps a score table that grows along both axes. The staircase from a corner finds a score in at most m + n - 1 steps (LeetCode 240: Search a 2D Matrix II).
A table is too big to list. The candidates are the entry values, and the check counts the entries at most a value with the staircase. The first value that counts at least k entries is the k-th smallest (LeetCode 378: Kth Smallest Element in a Sorted Matrix).
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 lowest rate that reaches a goal when the rate is a real number. Then explain how you stop the search and how you round the answer. 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 search the real rates between 0 and the top rate, and I write a check that says whether one rate reaches the target.
A higher rate never gives a lower balance, so the check is false and then true. There is no plus one for real numbers: a failed check moves the lower end to the middle.
I run a fixed 100 rounds, so that no tolerance can stall the loop, and I round up to the precision that the member needs.
When the answer is a real number, I still search for the first candidate that passes a monotone check. I write the check for one candidate, and I prove that a larger candidate never hurts.
I state the range: a value that cannot be the answer, and a value that surely passes. Then I halve the range a fixed 100 times. Real numbers have no plus one, so a failed check moves the lower end to the middle.
I do not stop on a tolerance. A tolerance below the gap between doubles never ends, and one that is too wide gives the wrong last digit. I round at the end, in the direction the problem needs.
For a grid sorted along rows and columns, I start in a corner. Each comparison discards a whole row or a whole column, so the walk takes at most m plus n steps.
Checkpoint · Real values
Q1/10 You search real rates between 0 and 0.05 for the lowest rate that reaches a target. At the middle rate the balance is below the target. What does the search do?
Answer: B
A rate that fails rules out every lower rate, so lo moves up to mid. Real numbers have no next value, so there is no mid + 1: adding 1 would jump past the whole range.
Q2/10 Why does the check "the balance after 36 months is at least the target" flip only once as the rate grows?
Answer: B
Each month's balance is the month before times (1 + rate), plus the deposit. A higher rate can only raise every month's balance, so once a rate passes, every higher rate passes.
Q3/10 The search loops while hi - lo is more than 0.000001, and then rounds lo up to a whole millionth. For 100 units a month, 36 months and a target of 4,500, it returns 12362. What is wrong?
Answer: B
After 16 rounds lo is 12361.9 millionths, which rounds up to 12362. At 12362 the balance is 4,499.9866, below the target. A fixed 100 rounds gives 12363.
Q4/10 Why does a loop that runs while hi - lo is more than 1e-18 never end for a rate near 0.0124?
Answer: C
After about 56 rounds the middle of the range equals one of its ends, and nothing changes. A fixed count of rounds always ends.
Q5/10 You search for the lowest rate that reaches a target, and for the square root of a number rounded down to a millionth. In which direction does each answer round?
Answer: C
A rate must reach the target, so it rounds up to a rate that surely works. A root truncated to six places rounds down. The direction comes from what the problem asks for.
Q6/10 After 100 rounds on the root of 4, lo is 1.9999999999999998. What does floor(lo × 1000000) give, and why does it matter?
Answer: B
The search approaches the root from below, so lo can sit one tiny step under an exact answer. Rounding it down loses a whole millionth. A check with whole numbers settles the last digit.
Q7/10 A grid is sorted along its rows and along its columns. You walk from the top-right corner to count the entries at most 8. The corner holds 9. What do you do?
Answer: B
9 is above 8, so everything below it in this column is above 8 too. The column holds no more entries that count, so you go left.
Q8/10 The staircase walk runs on a grid of 1,000 rows and 1,000 columns. At most how many steps does it take?
Answer: C
Each step discards one row or one column, so the walk ends after at most m + n - 1 steps: 1,000 + 1,000 - 1.
Q9/10 When is it correct to read a grid in reading order and run one binary search?
Answer: C
Only then is the whole reading order sorted. For the grid [[1, 4, 7], [2, 5, 8], [3, 6, 9]] the order 1, 4, 7, 2, ... is not sorted, and a flat search reports 2 as missing.
Q10/10 Which check would break a search over real rates?
Answer: B
Within 1 unit of 4,500 is true only for the rates 12351 to 12374 millionths, false before and false after. A search that sees a false at the first middle moves the wrong way and ends at 0.05.
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 | Square root to six places | Ads | Medium | A fixed number of rounds on real numbers, and an exact last digit |
| 2 | Count negatives in a sorted grid | Payments | Easy | A staircase walk that counts a whole row at once |
| 3 | Search a sorted grid by rows | Bank | Medium | One search over a grid whose rows continue one another |
| 4 | Search a grid sorted both ways | Search | Medium | A staircase search for one value |
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.