Find the first position not less than, or greater than, a value.
Use it when a sorted list has repeats, and you need to know where a value starts or ends, how many there are, or where it would go. Signal words: how many are smaller, how many are equal, the first and last position of, the rank of.
Start lo = 0 and hi = n. The window [lo, hi) holds the positions still in question.
Step while lo < hi, set mid = lo + (hi - lo) / 2. For the lower bound, move lo to mid + 1 when values[mid] < x, and otherwise set hi = mid. For the upper bound, use values[mid] <= x for that test.
Stop when lo == hi. The answer is lo, which can be n.
It does not work on a list that is not sorted by the same order as the test.
Cost: at most floor(log2 n) + 1 checks for each bound, O(log n), and O(1) extra space. The scan costs O(n).
In this lesson you use the first-true template on a sorted list that has repeats. You learn two searches, the lower bound and the upper bound. Together they tell you where a value starts, where it ends, how many copies there are, and where a missing value would go.
You work on the analytics of a bank app. Every day the app sorts the day's 2,000,000 card payments by amount, from the smallest to the largest. Many payments share an amount, because popular prices repeat.
Your team lead says: For any amount, show how many payments were smaller, how many were equal and how many were larger.
The dashboard asks about 50,000 amounts a day. Here is a short test with 7 payments: [2, 4, 4, 4, 7, 9, 9]. For the amount 4, one payment is smaller, three are equal and three are larger.
So the task is this: count the payments below, at and above an amount, without reading the whole list for every question.
A shelf of books is sorted by title, and several copies of one title sit side by side. To count the copies of a title, you do not read every spine. You find the slot where the copies start, and the slot right after where they end.
You open the shelf in the middle. If that title comes before yours, you ignore everything to its left. Otherwise the first copy is here or further left. After a few looks, you know the slot.
The number of copies is the gap between the two slots. If the title is not on the shelf, both slots are the same place, and the gap is zero.
Like counting copies on a sorted shelf: find the slot where the copies start and the slot after they end, and the gap is the count.
Before you write code, solve the test by hand. It shows what one question costs.
Solve it by hand: Seven payments: where does the amount 4 start?. The hand-solve sheet loads in your browser.
You take the amount 4 and compare it with every payment, from the first. You keep three tallies: smaller, equal and larger.
Payments: [2, 4, 4, 4, 7, 9, 9], and the amount is 4.
| Position | Payment | Against 4 | Smaller | Equal | Larger |
|---|---|---|---|---|---|
| 0 | 2 | smaller | 1 | 0 | 0 |
| 1 | 4 | equal | 1 | 1 | 0 |
| 2 | 4 | equal | 1 | 2 | 0 |
| 3 | 4 | equal | 1 | 3 | 0 |
| 4 | 7 | larger | 1 | 3 | 1 |
| 5 | 9 | larger | 1 | 3 | 2 |
| 6 | 9 | larger | 1 | 3 | 3 |
You made 7 comparisons. One question about a list of n payments costs n comparisons.
Start with a correct version. Compare the amount with every payment and keep three tallies.
def rank_counts(payments, x):
smaller = equal = larger = 0
for p in payments: # every payment
if p < x:
smaller += 1
elif p == x:
equal += 1
else:
larger += 1
return [smaller, equal, larger]This is correct. One question makes n comparisons: O(n). The team keeps it as the reference.
Now check the real size.
A day has 2,000,000 payments, and the dashboard asks about 50,000 amounts.
Here is the count:
So a dashboard refresh takes a quarter of an hour, and an analyst waits for every new set of amounts.
Predict the cost
Q A day has 2,000,000 payments, and the dashboard asks about 50,000 amounts. The first attempt compares every payment with every amount. About how many comparisons is that?
Answer: C
The count is 2,000,000 × 50,000 = 10^11. At about 10^8 steps a second, that is about 1,000 seconds.
The first attempt is correct, but it never uses the fact that the list is sorted. Now the team does.
Look at the sorted list again. The payments smaller than 4 come first. Then come the payments equal to 4, and then the larger ones. The list is cut into three blocks, and two boundaries separate them.
If you know the two boundaries, you know all three counts. The first boundary is where the block of 4s starts. The second is where it ends.
Each boundary is a first-true question from the last lesson. The start of the 4s is the first position where "the payment is at least 4" is true. The end is the first position where "the payment is more than 4" is true.
| Position | 0 | 1 | 2 | 3 | 4 | 5 | 6 |
|---|---|---|---|---|---|---|---|
| Payment | 2 | 4 | 4 | 4 | 7 | 9 | 9 |
| At least 4? | no | yes | yes | yes | yes | yes | yes |
| More than 4? | no | no | no | no | yes | yes | yes |
Each row of answers is false and then true for ever, because the payments are sorted. The first "yes" in the second row is at position 1, and in the third row at position 4.
These two positions have names. The first position whose value is not below 4 is the lower bound, here 1. The first position whose value is above 4 is the upper bound, here 4.
The counts follow. Smaller is the lower bound, 1. Equal is the upper bound minus the lower bound, 4 − 1 = 3. Larger is n minus the upper bound, 7 − 4 = 3.
In a sorted list the smaller, equal and larger payments form three blocks, so two boundaries, the lower and the upper bound, give all three counts.
Race: Scan the list, against the lower and upper bound searches. The operation counter loads in your browser.
The race counts the worst case for one amount. At 100,000 payments the scan makes 100,000 comparisons, and the two searches make 34 checks. At the real 2,000,000 payments, the two searches make at most 42 checks, so 50,000 amounts need about 2 million checks and not 10^11.
The payments are [1, 3, 4, 4, 4, 4, 6, 8], and the amount is 4. The player runs the upper bound, the first position whose value is above 4. It stops at six steps and asks you to predict.
Dry run: Predict each step: where does the amount 4 end?. 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 | Value at mid | What moves |
|---|---|---|---|---|---|
| 1 | 0 | 8 | 4 | 4 | 4 is at most 4, so lo moves to 5 |
| 2 | 5 | 8 | 6 | 6 | 6 is above 4, so hi moves to 6 |
| 3 | 5 | 6 | 5 | 4 | 4 is at most 4, so lo moves to 6 |
| end | 6 | 6 | none | the window is empty, so the answer is 6 |
Look at step 1. The middle value equals the amount, but the upper bound looks for a value above it, so lo moves past the equal value.
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 2 the window is [5, 8), which holds positions 5, 6 and 7. The middle is position 6, which holds a 6. That is above 4, so it may be the first value above 4, and hi moves to 6, not to 5.
At step 3 the window is [5, 6). It holds one position, so the middle is position 5 itself. It holds a 4, which is at most 4, so it is ruled out, and lo moves to 6.
Now lo == hi == 6, the window is empty, and the upper bound is 6. The lower bound of 4 on the same list ends differently. There the test is values[mid] < 4, so an equal value at the middle keeps its place, and hi moves onto it. The window closes in front of the first 4, at position 2.
Here is the rule that keeps both searches correct. Every line of the templates exists to protect it.
Every value before lo is below the target, and every value from hi on is not, so lo ends as the lower bound.
For the upper bound, read "at most the target" for "below the target", and lo ends as the upper bound. At the start lo = 0 and hi = n, so no value is before lo, and position n counts as past the end. The rule holds.
If values[mid] is below the target, then every value up to mid is below it too, because the list is sorted. So lo = mid + 1 keeps the rule. If it is not below, then every value from mid on is not below, so hi = mid keeps the rule.
The loop ends for the same reason as in the last lesson. The middle is always inside the window, and every step at least halves it, so a list of n values needs at most floor(log2 n) + 1 checks. When lo == hi, lo is the bound.
Use it when a sorted list has repeats, and you need to know where a value starts or ends, how many there are, or where it would go. Signal words: how many are smaller, how many are equal, the first and last position of, the rank of.
Start: lo = 0 and hi = n. The window [lo, hi) holds the positions still in question.
Step: while lo < hi, set mid = lo + (hi - lo) / 2. For the lower bound, move lo to mid + 1 when values[mid] < x, and otherwise set hi = mid. For the upper bound, use values[mid] <= x for that test.
Stop: when lo == hi. The answer is lo, which can be n.
It does not work on a list that is not sorted by the same order as the test.
Cost: at most floor(log2 n) + 1 checks for each bound, O(log n), and O(1) extra space. The scan costs O(n).
def lower_bound(values, x):
# [1] The window [lo, hi): values before lo are below x, 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] < x:
# [3] A value below x rules out itself and every value before it, so lo moves past it.
lo = mid + 1
else:
# [4] A value that is not below x 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 not below x, or n.
return lopublic int lowerBound(int[] values, int x) {
// [1] The window [lo, hi): values before lo are below x, 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] < x) {
// [3] A value below x rules out itself and every value before it, so lo moves past it.
lo = mid + 1;
} else {
// [4] A value that is not below x 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 not below x, or n.
return lo;
}int lowerBound(vector<int>& values, int x) {
// [1] The window [lo, hi): values before lo are below x, 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] < x) {
// [3] A value below x rules out itself and every value before it, so lo moves past it.
lo = mid + 1;
} else {
// [4] A value that is not below x 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 not below x, or n.
return lo;
}function lowerBound(values, x) {
// [1] The window [lo, hi): values before lo are below x, 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] < x) {
// [3] A value below x rules out itself and every value before it, so lo moves past it.
lo = mid + 1;
} else {
// [4] A value that is not below x 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 not below x, or n.
return lo;
}Rebuild the template: put its lines back in order. Loads in your browser.
def upper_bound(values, x):
# [1] The window [lo, hi): values before lo are at most x, values from hi on are above x, and position n counts as above.
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] <= x:
# [3] A value at most x rules out itself and every value before it, so lo moves past it.
lo = mid + 1
else:
# [4] A value above x 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 above x, or n.
return lopublic int upperBound(int[] values, int x) {
// [1] The window [lo, hi): values before lo are at most x, values from hi on are above x, and position n counts as above.
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] <= x) {
// [3] A value at most x rules out itself and every value before it, so lo moves past it.
lo = mid + 1;
} else {
// [4] A value above x 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 above x, or n.
return lo;
}int upperBound(vector<int>& values, int x) {
// [1] The window [lo, hi): values before lo are at most x, values from hi on are above x, and position n counts as above.
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] <= x) {
// [3] A value at most x rules out itself and every value before it, so lo moves past it.
lo = mid + 1;
} else {
// [4] A value above x 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 above x, or n.
return lo;
}function upperBound(values, x) {
// [1] The window [lo, hi): values before lo are at most x, values from hi on are above x, and position n counts as above.
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] <= x) {
// [3] A value at most x rules out itself and every value before it, so lo moves past it.
lo = mid + 1;
} else {
// [4] A value above x 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 above x, or n.
return lo;
}Compare the two. Everything is the same except the test in the loop, < against <=. The lower bound stops lo in front of the equal values. The upper bound moves lo past them.
The lower and upper bound are the same search with one test changed: less than for the lower bound, less than or equal to for the upper bound.
Exercise · Predict the output: Where do the two bounds land?. A sorted list holds three 5s. One loop runs twice: first as the lower bound of 5, then as the upper bound of 5. What does it print: the two positions, then their difference?
values = [3, 5, 5, 5, 8, 8, 12]
x = 5
results = []
for inclusive in (False, True):
lo, hi = 0, len(values)
while lo < hi:
mid = lo + (hi - lo) // 2
if values[mid] < x or (inclusive and values[mid] == x):
lo = mid + 1
else:
hi = mid
results.append(lo)
print(*results, results[1] - results[0])Exercise · Find the bug: The upper bound that stops at the first copy. This function should return the first position whose value is above x, but it gives the wrong position when x is in the list. Which line is wrong?
def upper_bound(values, x):
lo, hi = 0, len(values)
while lo < hi:
mid = lo + (hi - lo) // 2
if values[mid] < x:
lo = mid + 1
else:
hi = mid
return loOnce you have both bounds, many questions about a sorted list become one line.
| Question | Answer, with lower and upper for the value x |
|---|---|
How many values are below x? |
lower |
How many values are at most x? |
upper |
How many values are above x? |
n - upper |
How many copies of x? |
upper - lower |
Is x in the list? |
lower < n and values[lower] == x |
| Where is the first copy? | lower, when x is in the list |
| Where is the last copy? | upper - 1, when x is in the list |
Where would a new x go? |
lower, in front of the copies, or upper, after them |
How many values lie in [low, high]? |
upper(high) - lower(low) |
When x is missing, lower and upper are equal. Both give the position where x would be inserted, and the number of copies is zero.
For whole numbers you can write upper(x) as lower(x + 1). It does not work for decimals or text, and x + 1 can overflow in Java and C++ when x is the largest int. The test with <= is safe for every type.
A delivery app keeps its sorted time estimates in minutes: [12, 15, 15, 18, 20, 20, 20, 25]. How many deliveries take exactly 20 minutes, and what is the next slower time?
There are 8 values. The lower bound of 20 is 4, because 12, 15, 15 and 18 are below it. The upper bound of 20 is 7, because the three 20s are at most 20.
| Question | Calculation | Answer |
|---|---|---|
| Copies of 20 | upper − lower = 7 − 4 | 3 |
| First and last position of 20 | lower, and upper − 1 | 4 and 6 |
| Next slower time | the value at position upper |
25 |
| Deliveries of 15 to 20 minutes | upper(20) − lower(15) = 7 − 1 | 6 |
Only the question changed. The searches are the same two templates.
Exercise · Put it in order: Is this payment in the list?. Arrange the lines into a function that says whether x is in a sorted list, using the lower bound.
def contains(values, x):
lo = 0
hi = len(values)
while lo < hi:
mid = lo + (hi - lo) // 2
if values[mid] < x:
lo = mid + 1
else:
hi = mid
return lo < len(values) and values[lo] == x
return values[lo] == xMost languages ship these searches, and it is worth knowing which. This table was checked by running each one on [2, 4, 4, 4, 7, 9, 9].
| Language | Lower bound | Upper bound | Notes |
|---|---|---|---|
| Python | bisect.bisect_left(a, x) |
bisect.bisect_right(a, x), also named bisect.bisect |
Returns a position. key= is available from Python 3.10 |
| C++ | std::lower_bound(a.begin(), a.end(), x) |
std::upper_bound(a.begin(), a.end(), x) |
Returns an iterator: subtract a.begin() for the position. std::equal_range returns both |
| Java | none for arrays | none for arrays | Arrays.binarySearch is different: see below |
| JavaScript | none | none | Write the template. indexOf is a scan, and sort() sorts numbers as text unless you pass a comparator |
Results on [2, 4, 4, 4, 7, 9, 9], with positions counted from 0. The Java column is what one run returned, and for a repeated value another JDK may return another copy:
x |
Lower bound | Upper bound | Java Arrays.binarySearch |
|---|---|---|---|
| 1 (below everything) | 0 | 0 | -1 |
| 2 | 0 | 1 | 0 |
| 4 (three copies) | 1 | 4 | 3 |
| 5 (missing) | 4 | 4 | -5 |
| 9 | 5 | 7 | 5 |
| 10 (above everything) | 7 | 7 | -8 |
Python's bisect_left and bisect_right and C++'s std::lower_bound and std::upper_bound gave exactly the two bound columns, for these values and for an empty list, where both are 0.
Java's Arrays.binarySearch has two traps.
First, with repeats it returns the position of a matching copy, and its documentation says that there is no guarantee which one. It stops at the first equal value it happens to reach. In this run it returned position 3 for the three 4s, the last one, and position 1 for [4, 4, 4, 4], neither the first nor the last. Treat the result as any matching index, never as a rule you can rely on.
Second, for a missing value it returns a negative number, -(insertion point) - 1. For 5 it gave -5, so the insertion point is -(-5) - 1 = 4, which is the lower bound.
A common trap: Java's binary search returns the position of some copy, and which one is unspecified, so use your own lower bound for the first copy.
lo, hi and mid, so the extra space is O(1).Real production data brings edge cases.
Before the first payment, values = []. The window is [0, 0), the loop never runs, and both bounds are 0. The counts are 0 smaller, 0 equal and 0 larger.
For values = [5, 5, 5], the lower bound of 5 is 0 and the upper bound is 3, so there are 3 copies. For the value 4 both bounds are 0, and for the value 6 both bounds are 3, the end of the list.
For values = [2, 4, 7], the value 1 has both bounds at 0, and the value 10 has both bounds at 3. A bound can be n, so you must check lower < n before you read values[lower].
For values = [7], the value 7 has the lower bound 0 and the upper bound 1. The value 6 has both bounds at 0, and the value 8 has both at 1. A window of one value must end in one step.
This version returns mid as soon as values[mid] == x, as a search for one value does. With repeats, the middle can be any of the copies.
Counterexample: values = [2, 4, 4, 4, 7] and x = 4. The middle is position 2, which holds a 4, so the bug returns 2 as the first copy. The first copy is at position 1.
Java's Arrays.binarySearch stops at an equal value in the same way, and in a test run it also returned 2 for this list. Keep searching until the window is empty.
A common mistake: returning mid as soon as it equals x. With repeats the middle can be any copy, so the search must continue.
This version reports upper as the position of the last copy. The upper bound is the first position after the copies, so it is one too far.
Counterexample: values = [4, 4, 4, 7] and x = 4. The upper bound is 3, so the bug reports 3, which holds the value 7. The last copy is at position 2, which is upper - 1.
This version checks whether x is present with values[lower] == x, and does not check that lower < n first.
Counterexample: values = [2, 4, 4] and x = 10. The lower bound is 3, which equals n, so values[3] is read outside the list. Python raises an error, Java throws an exception, and C++ reads memory it does not own.
Write the check as lower < n and values[lower] == x.
This version reads the negative result of Arrays.binarySearch as -r, and takes it as the insertion point. The result is -(insertion point) - 1, so the insertion point is -r - 1.
Counterexample: values = [2, 4, 7] and x = 5. Java returns -3. The bug reads 3, but the correct insertion point is 2, in front of the 7.
Exercise · Break it: Find the value this lookup reports as found. This function returns the position of the last copy of x, or -1 when x is missing. It returns upper minus 1 and never checks that x is there. Find an input where it gives the wrong answer.
def last_position(values, x):
lo, hi = 0, len(values)
while lo < hi:
mid = lo + (hi - lo) // 2
if values[mid] <= x:
lo = mid + 1
else:
hi = mid
return lo - 1Your team lead hands you a list of payments in the order they arrived: [5, 1, 9, 3, 7]. You ask for the lower bound of 7.
The search checks position 2, a 9, which is not below 7, so it moves hi to 2. Then position 1, a 1, is below 7, so lo moves to 2. It returns 2.
But 7 is at position 4, so the answer 2 is wrong. The test "the value is below 7" is not false and then true on this list. Sort the list first, or use a scan or a hash map.
Your team lead brings four product changes. Each one is a different question about the same two bounds.
A dashboard wants "this payment is larger than 57% of the day's payments". The number below it is the lower bound, so the share is lower / n.
Finance wants the number of payments between 100 and 500, both included. That is upper(500) - lower(100). It needs no scan of the payments in between.
A support tool wants the block of positions that hold one amount. The block starts at lower and ends at upper - 1. If the two bounds are equal, the amount is missing (LeetCode 34: Find First and Last Position of Element in Sorted Array).
A chat app jumps to the first channel whose letter is strictly after the key, and wraps to the first channel when none is. That is the upper bound, and n becomes position 0 (LeetCode 744: Find Smallest Letter Greater Than Target).
Explain it back: write the idea in your own words and get feedback.
In two or three sentences, explain to a teammate how you count the copies of a value in a sorted list without reading the list. Then explain which single change turns a lower bound into an upper bound. 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.
The list is sorted, so the copies of a value form one block. I find where the block starts with a lower bound, and where it ends with an upper bound.
Both are the first-true search. The lower bound moves lo past a value that is below x. The upper bound moves lo past a value that is at most x. That one operator is the only difference.
The number of copies is upper minus lower. If they are equal, the value is missing. That is log n checks for each bound.
The straightforward answer scans the whole list for every question, which costs n steps. When the list is sorted, I use two binary searches instead.
The lower bound is the first position whose value is not below x. The upper bound is the first position whose value is above x. Both are the first-true template. The lower bound moves lo past a value that is below x, and the upper bound moves lo past a value that is at most x.
With both, the number of copies is upper minus lower. The first copy is at lower, and the last is at upper minus 1. If the two are equal, x is missing, and that position is where it would go.
Each search costs about log n steps. In Python I would call bisect left and bisect right, and in C plus plus lower bound and upper bound. Java's binary search may return any copy, and JavaScript has none, so there I write the loop.
Checkpoint · The two bounds
Q1/3 The list is [2, 4, 4, 4, 7, 9, 9]. What is the lower bound of 4?
Answer: B
The lower bound is the first position whose value is not below 4. Position 0 holds 2, which is below 4, and position 1 holds the first 4.
Q2/3 For the same list, what is the upper bound of 4?
Answer: C
The upper bound is the first position whose value is above 4. The three 4s fill positions 1 to 3, and position 4 holds 7.
Q3/3 How many copies of x are in a sorted list?
Answer: C
The copies fill the positions from the lower bound up to, but not including, the upper bound. For the 4s above, 4 − 1 = 3.
Checkpoint · The code
Q1/3 Two loops are the same, except for one test. For the lower bound lo moves past a value when it is below x. What is the test for the upper bound?
Answer: B
The upper bound moves lo past every value that is at most x, so equal values are skipped too. That is the single change from < to <=.
Q2/3 The list is [2, 4, 7]. What do the lower bound and the upper bound of 5 return?
Answer: B
The values 2 and 4 are below 5, and 7 is above it. Both searches stop at position 2, where a 5 would go. When the two bounds are equal, the value is missing.
Q3/3 The list is [4, 4, 4, 7] and the value is 4. Where is the last copy of 4?
Answer: B
The upper bound is 3, the first position after the copies. The last copy is one position earlier, at 2. Position 3 holds the 7.
Checkpoint · Built-ins and traps
Q1/4 In Java, Arrays.binarySearch on [2, 4, 7] for the value 5 returns -3. Where would 5 be inserted?
Answer: B
The result for a missing value is -(insertion point) - 1. So the insertion point is -(-3) - 1 = 2, which is in front of the 7.
Q2/4 A sorted list holds three copies of 4. What does Arrays.binarySearch return for 4?
Answer: C
Java only promises to find a copy. For [2, 4, 4, 4, 7, 9, 9] it returned 3, and for [4, 4, 4, 4] it returned 1.
Q3/4 Which Python call gives the upper bound of x?
Answer: B
bisect_right returns the first position after the copies of x, which is the upper bound. bisect_left returns the lower bound. The last two options scan the list.
Q4/4 Why can you not use a lower bound search on [5, 1, 9, 3, 7]?
Answer: C
Both bounds rely on the test being false and then true for ever. On an unsorted list that is not true, so the search can return a wrong position.
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 | Smallest letter greater than the key | Chat | Easy | The upper bound, with a wrap round at the end |
| 2 | Count elements within a score band | Ads | Easy | Two bounds, and the gap between them as a count |
| 3 | Closest element to a target | Shop | Easy | The values on both sides of a bound |
| 4 | First and last occurrence of a code | Monitoring | Medium | Both bounds, a block of repeats, and a missing 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.