Binary search when the array is sorted only in parts.
Use it when a sorted list was rotated, so it has two sorted runs and one break. You need its smallest value or a search for a value. Signal words: sorted but the start moved, a ring buffer that wrapped, rotated by an unknown amount.
Start lo = 0 and hi = n. The condition is values[mid] > values[n - 1]: true means that mid is in the first run.
Step while lo < hi, set mid = lo + (hi - lo) / 2. If the condition is true, set lo = mid + 1. Otherwise set hi = mid.
Stop when lo == hi. The answer is lo, the position of the smallest value. To search, pick the run with the last value, and use the lower bound inside it.
It does not work on a list with more than one break, or on a list with repeats at both ends.
Cost: at most floor(log2 n) + 1 checks for the break, O(log n), and O(1) extra space. The scan costs O(n).
In this lesson you use the first-true template on lists that are sorted only in parts. You search a rotated list for an id, and you find its smallest id. You also find a peak in a list that climbs and falls. Then you see what repeated values do to these searches, and why the worst case becomes linear.
You work on the fraud checks of a bank app. The app keeps the ids of the last 1,000,000 flagged card transactions in a ring buffer, a fixed row of slots. When the row is full, each new id overwrites the oldest one.
Ids only grow with time. So after the ring wraps, it reads as a sorted list that starts in the middle. Here is a short ring of 10 slots: [62, 67, 71, 75, 80, 3, 8, 14, 21, 27]. The ids 3 to 27 are the oldest, and 62 to 80 came later.
Your team lead says: Analysts look up a transaction id about 30,000 times a day. For each id, tell me which slot holds it, or that it is gone. Also tell me the slot of the oldest id.
So the task is this: find the slot of an id, and the slot of the oldest id, without reading the whole ring every time.
Take a deck sorted from the lowest card to the highest. Cut it once, and put the lower part under the higher part. The deck is not sorted any more, but it still has two sorted parts and one break between them.
To find a card, first find the cut. A card higher than the last card of the deck is in the first part. Any other card is in the second part. Then look for the card inside that one sorted part.
If the deck was never cut, there is only one part, and the cut is at the very top.
Like a cut deck of cards: it still has two sorted parts and one break, so find the cut first and then search one part.
Before you write code, solve the test by hand. It shows what one question costs.
Solve it by hand: A ring of ten ids: where does the second run start?. The hand-solve sheet loads in your browser.
You look for the id 14. You compare it with every slot, from the first, until you find it.
Ring: [62, 67, 71, 75, 80, 3, 8, 14, 21, 27], and the id is 14.
| Slot | Id in the slot | Equal to 14? | Comparisons so far |
|---|---|---|---|
| 0 | 62 | no | 1 |
| 1 | 67 | no | 2 |
| 2 | 71 | no | 3 |
| 3 | 75 | no | 4 |
| 4 | 80 | no | 5 |
| 5 | 3 | no | 6 |
| 6 | 8 | no | 7 |
| 7 | 14 | yes | 8 |
You made 8 comparisons. An id that is missing costs 10, one comparison for every slot. For a ring of n slots, one question costs up to n comparisons.
Start with a correct version. Walk through the slots and stop when the id is found.
def find_id(ring, x):
for slot in range(len(ring)): # every slot, from the first
if ring[slot] == x:
return slot
return -1 # the id is not in the ringThis is correct. One question makes up to n comparisons: O(n). The oldest id needs another scan for the smallest value. The team keeps both as the reference.
Now check the real size.
The ring has 1,000,000 slots, and analysts ask about 30,000 ids a day.
Here is the count:
So a batch of look-ups takes five minutes, and the analysts wait for every new batch.
Predict the cost
Q The ring has 1,000,000 slots and analysts ask about 30,000 ids. The first attempt compares every id with every slot. About how many comparisons is that, in the worst case?
Answer: C
The count is 1,000,000 × 30,000 = 3 × 10^10. At about 10^8 steps a second, that is about 300 seconds.
The first attempt is correct, but it ignores the order inside the ring. Now the team uses it.
Try the usual binary search first. Look at slot 5 of the ring. It holds 3, which is below 67, so the usual search moves right. But 67 is in slot 1, on the left, so the usual search wrongly says that 67 is missing.
The ring is a rotated list. Read it again: 62, 67, 71, 75, 80 and then 3, 8, 14, 21, 27. It has two sorted runs, and one break between them. Each run is sorted, and every id in the first run is above every id in the second run.
That gives a test with one flip. Compare an id with the last id of the ring, which is 27. Every id in the first run is above 27. Every id in the second run is at most 27.
| Position | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 |
|---|---|---|---|---|---|---|---|---|---|---|
| Id | 62 | 67 | 71 | 75 | 80 | 3 | 8 | 14 | 21 | 27 |
| At most 27? | no | no | no | no | no | yes | yes | yes | yes | yes |
The answers read no, no, no, no, no, yes, yes, yes, yes, yes. That is false and then true for ever, the same shape as in the first lesson. The first true position is 5, where the second run starts. So slot 5 holds the smallest id, the oldest one.
That answers the second question of the team lead.
Now an id. If it is above the last id, it can only be in the first run. Otherwise it can only be in the second run. Then you search that one run with the lower bound from the last lesson, and check that the id found is equal.
Ids above the last id come first and ids at or below it come second, so a first-true search on that test finds where the second run starts.
Race: Scan the ring, against the break search and the run search. The operation counter loads in your browser.
The race counts the worst case for one id. At 100,000 slots the scan makes 100,000 comparisons, and the two searches make at most 34. At the real 1,000,000 slots, the two searches make at most 40 checks, so 30,000 ids need about 1.2 million checks and not 3 × 10^10. The start of the second run changes only when the ring changes, so you can find it once and reuse it.
The ring is [47, 52, 58, 60, 66, 71, 2, 9, 15, 23, 31], and the last id is 31. The player looks for the first position whose id is at most 31. It stops at six steps and asks you to predict.
Dry run: Predict each step: eleven ids, the second run starts at position 6. 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 | Id at mid | What moves |
|---|---|---|---|---|---|
| 1 | 0 | 11 | 5 | 71 | 71 is above 31, so lo moves to 6 |
| 2 | 6 | 11 | 8 | 15 | 15 is at most 31, so hi moves to 8 |
| 3 | 6 | 8 | 7 | 9 | 9 is at most 31, so hi moves to 7 |
| 4 | 6 | 7 | 6 | 2 | 2 is at most 31, so hi moves to 6 |
| end | 6 | 6 | none | the window is empty, so the second run starts at 6 |
Look at step 1. The middle id is above 31, so it is in the first run. It rules out itself and every id before it.
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 3 the window is [6, 8), which holds positions 6 and 7. The middle is position 7, with the id 9. It is at most 31, so it may be the first id of the second run, and hi moves to 7. Position 7 leaves the window, but position 6 stays.
At step 4 the window is [6, 7). It holds one position, so the middle is position 6 itself, with the id 2. It is at most 31, so hi moves to 6.
Now lo == hi == 6, the window is empty, and the second run starts at position 6. The id 2 is the smallest id of the ring.
Here is the rule that keeps the search for the break correct. Every line of the template exists to protect it.
Every position before lo is in the first run, and every position from hi on is in the second, so lo ends where the second run starts.
At the start lo = 0 and hi = n. No position is before 0, and position n counts as at or below the last id, so the rule holds.
If the id at mid is above the last id, it is in the first run, and so is every id before it. So lo = mid + 1 keeps the rule. If it is at most the last id, it is in the second run, and so is every id after it. So hi = mid keeps the rule.
The loop ends for the same reason as before. The middle is always inside the window, and every step at least halves it. When lo == hi, lo is the first position of the second run. If the list is not rotated, every id is at most the last id, and the search returns 0.
Use it when a sorted list was rotated, so it has two sorted runs and one break. You need its smallest value or a search for a value. Signal words: sorted but the start moved, a ring buffer that wrapped, rotated by an unknown amount.
Start: lo = 0 and hi = n. The condition is values[mid] > values[n - 1]: true means that mid is in the first run.
Step: while lo < hi, set mid = lo + (hi - lo) / 2. If the condition is true, set lo = mid + 1. Otherwise set hi = mid.
Stop: when lo == hi. The answer is lo, the position of the smallest value. To search, pick the run with the last value, and use the lower bound inside it.
It does not work on a list with more than one break, or on a list with repeats at both ends.
Cost: at most floor(log2 n) + 1 checks for the break, O(log n), and O(1) extra space. The scan costs O(n).
def rotation_start(values):
n = len(values)
# [1] The window [lo, hi): positions before lo hold ids above the last id, positions from hi on hold ids at or below it, and position n counts as at or below.
lo = 0
hi = n
# [2] While the window holds a position, look at the id in its middle.
while lo < hi:
mid = lo + (hi - lo) // 2
if values[mid] > values[n - 1]:
# [3] An id above the last id is in the first run, so it and every id before it is ruled out: lo moves past it.
lo = mid + 1
else:
# [4] An id at or below the last id is in the second run, so it may be the first of it: hi moves to it.
hi = mid
# [5] The window is empty: lo is where the second run starts, which holds the smallest id. It is 0 when the list is not rotated.
return lopublic int rotationStart(int[] values) {
int n = values.length;
// [1] The window [lo, hi): positions before lo hold ids above the last id, positions from hi on hold ids at or below it, and position n counts as at or below.
int lo = 0;
int hi = n;
// [2] While the window holds a position, look at the id in its middle.
while (lo < hi) {
int mid = lo + (hi - lo) / 2;
if (values[mid] > values[n - 1]) {
// [3] An id above the last id is in the first run, so it and every id before it is ruled out: lo moves past it.
lo = mid + 1;
} else {
// [4] An id at or below the last id is in the second run, so it may be the first of it: hi moves to it.
hi = mid;
}
}
// [5] The window is empty: lo is where the second run starts, which holds the smallest id. It is 0 when the list is not rotated.
return lo;
}int rotationStart(vector<int>& values) {
int n = (int)values.size();
// [1] The window [lo, hi): positions before lo hold ids above the last id, positions from hi on hold ids at or below it, and position n counts as at or below.
int lo = 0;
int hi = n;
// [2] While the window holds a position, look at the id in its middle.
while (lo < hi) {
int mid = lo + (hi - lo) / 2;
if (values[mid] > values[n - 1]) {
// [3] An id above the last id is in the first run, so it and every id before it is ruled out: lo moves past it.
lo = mid + 1;
} else {
// [4] An id at or below the last id is in the second run, so it may be the first of it: hi moves to it.
hi = mid;
}
}
// [5] The window is empty: lo is where the second run starts, which holds the smallest id. It is 0 when the list is not rotated.
return lo;
}function rotationStart(values) {
const n = values.length;
// [1] The window [lo, hi): positions before lo hold ids above the last id, positions from hi on hold ids at or below it, and position n counts as at or below.
let lo = 0;
let hi = n;
// [2] While the window holds a position, look at the id in its middle.
while (lo < hi) {
const mid = lo + Math.floor((hi - lo) / 2);
if (values[mid] > values[n - 1]) {
// [3] An id above the last id is in the first run, so it and every id before it is ruled out: lo moves past it.
lo = mid + 1;
} else {
// [4] An id at or below the last id is in the second run, so it may be the first of it: hi moves to it.
hi = mid;
}
}
// [5] The window is empty: lo is where the second run starts, which holds the smallest id. It is 0 when the list is not rotated.
return lo;
}Rebuild the template: put its lines back in order. Loads in your browser.
This template reuses the first one. It finds the start of the second run, picks the run, and runs the lower bound inside it.
def search_rotated(values, x):
n = len(values)
# [1] An empty list holds nothing.
if n == 0:
return -1
# [2] Find where the second run starts, with the first-true search from the break template.
lo = 0
hi = n
while lo < hi:
mid = lo + (hi - lo) // 2
if values[mid] > values[n - 1]:
lo = mid + 1
else:
hi = mid
start = lo
# [3] An id above the last id can only be in the first run, positions 0 to start - 1. Any other id can only be in the second run.
if x > values[n - 1]:
lo = 0
hi = start
else:
lo = start
hi = n
end = hi
# [4] Inside that run, find the first id that is not below x, as in the lower bound.
while lo < hi:
mid = lo + (hi - lo) // 2
if values[mid] < x:
lo = mid + 1
else:
hi = mid
# [5] The id is present only if the search stopped inside the run, on an id equal to x.
if lo < end and values[lo] == x:
return lo
return -1public int searchRotated(int[] values, int x) {
int n = values.length;
// [1] An empty list holds nothing.
if (n == 0) {
return -1;
}
// [2] Find where the second run starts, with the first-true search from the break template.
int lo = 0;
int hi = n;
while (lo < hi) {
int mid = lo + (hi - lo) / 2;
if (values[mid] > values[n - 1]) {
lo = mid + 1;
} else {
hi = mid;
}
}
int start = lo;
// [3] An id above the last id can only be in the first run, positions 0 to start - 1. Any other id can only be in the second run.
if (x > values[n - 1]) {
lo = 0;
hi = start;
} else {
lo = start;
hi = n;
}
int end = hi;
// [4] Inside that run, find the first id that is not below x, as in the lower bound.
while (lo < hi) {
int mid = lo + (hi - lo) / 2;
if (values[mid] < x) {
lo = mid + 1;
} else {
hi = mid;
}
}
// [5] The id is present only if the search stopped inside the run, on an id equal to x.
if (lo < end && values[lo] == x) {
return lo;
}
return -1;
}int searchRotated(vector<int>& values, int x) {
int n = (int)values.size();
// [1] An empty list holds nothing.
if (n == 0) {
return -1;
}
// [2] Find where the second run starts, with the first-true search from the break template.
int lo = 0;
int hi = n;
while (lo < hi) {
int mid = lo + (hi - lo) / 2;
if (values[mid] > values[n - 1]) {
lo = mid + 1;
} else {
hi = mid;
}
}
int start = lo;
// [3] An id above the last id can only be in the first run, positions 0 to start - 1. Any other id can only be in the second run.
if (x > values[n - 1]) {
lo = 0;
hi = start;
} else {
lo = start;
hi = n;
}
int end = hi;
// [4] Inside that run, find the first id that is not below x, as in the lower bound.
while (lo < hi) {
int mid = lo + (hi - lo) / 2;
if (values[mid] < x) {
lo = mid + 1;
} else {
hi = mid;
}
}
// [5] The id is present only if the search stopped inside the run, on an id equal to x.
if (lo < end && values[lo] == x) {
return lo;
}
return -1;
}function searchRotated(values, x) {
const n = values.length;
// [1] An empty list holds nothing.
if (n === 0) {
return -1;
}
// [2] Find where the second run starts, with the first-true search from the break template.
let lo = 0;
let hi = n;
while (lo < hi) {
const mid = lo + Math.floor((hi - lo) / 2);
if (values[mid] > values[n - 1]) {
lo = mid + 1;
} else {
hi = mid;
}
}
const start = lo;
// [3] An id above the last id can only be in the first run, positions 0 to start - 1. Any other id can only be in the second run.
if (x > values[n - 1]) {
lo = 0;
hi = start;
} else {
lo = start;
hi = n;
}
const end = hi;
// [4] Inside that run, find the first id that is not below x, as in the lower bound.
while (lo < hi) {
const mid = lo + Math.floor((hi - lo) / 2);
if (values[mid] < x) {
lo = mid + 1;
} else {
hi = mid;
}
}
// [5] The id is present only if the search stopped inside the run, on an id equal to x.
if (lo < end && values[lo] === x) {
return lo;
}
return -1;
}To search a rotated list, compare the id with the last id to choose the run, and then run the lower bound inside that run.
Exercise · Find the bug: The id that is the last one. The second run of a rotated list starts at position start. This function picks the run that can hold x, then runs a lower bound inside it. It misses an id that is there, for one particular x. Which line is wrong?
def search_run(values, start, x):
n = len(values)
if x >= values[n - 1]:
lo, hi = 0, start
else:
lo, hi = start, n
end = hi
while lo < hi:
mid = lo + (hi - lo) // 2
if values[mid] < x:
lo = mid + 1
else:
hi = mid
if lo < end and values[lo] == x:
return lo
return -1A maps app prints the departures of a night route as minutes since midnight. The printout starts at the first bus after 20:30, so the list runs past midnight: [1230, 1290, 1350, 1410, 30, 90, 150, 210]. When is the first bus after midnight, and does a bus leave at minute 90?
The last value is 210. The break search checks position 4, with 30, which is at most 210, so hi moves to 4. Then positions 2 and 3 hold 1350 and 1410, which are above 210, so lo moves to 3 and then to 4. The second run starts at position 4, so the first bus after midnight leaves at minute 30.
| Question | Calculation | Answer |
|---|---|---|
| First bus after midnight | the id at the start of the second run | 30, at position 4 |
| A bus at minute 90? | 90 is at most 210, so search positions 4 to 7 for the first value not below 90 | yes, at position 5 |
| A bus at minute 1300? | 1300 is above 210, so search positions 0 to 3 | no, the first value not below 1300 is 1350 |
Only the question changed. The two searches are the templates above, with 3 checks for the break and 3 for the minute 90.
Now a list with no sorted run at all. A cycling app records the height of a route every 100 metres: [112, 155, 121, 134, 118, 190, 127]. A rider wants one high point, a position that is higher than the two next to it. Position 0 and the last position have only one neighbour, and the outside counts as lower.
Call such a position a peak. Here there are three: 155, 134 and 190. The list does not need to be sorted for a peak to exist. The highest value is always a peak, so a list with distinct neighbours always has at least one.
The search compares the middle with the position after it. If the list climbs there, a peak lies after the middle. If it falls, the middle is a peak, or a peak lies before it.
The list climbs into lo, and hi is higher than the position after it or is the last position, so a peak lies between lo and hi.
Why the invariant holds, and why a peak lies between lo and hi:
lo = 0 has nothing before it, and hi = n - 1 is the last position. The rule holds.mid to mid + 1, the new lo = mid + 1 has a lower position before it. The rule holds. The middle is below hi, so mid + 1 is still inside the window.mid to mid + 1, the new hi = mid is higher than the position after it. The rule holds.So walking toward the higher neighbour always ends on a peak. The window shrinks every step, so the walk ends. When the window is empty, lo == hi, the stretch from lo to hi is one position, and that position is a peak.
This is the first-true template with a new condition, "the next value is lower", and hi starting at n - 1. The last position counts as true, because nothing follows it. But on a list with several peaks the condition flips back and forth, so the proof does not use "false and then true". It uses the invariant above.
def find_peak(values):
# [1] The window [lo, hi): the list climbs into lo, and hi is higher than the position after it, or is the last position, which is never compared.
lo = 0
hi = len(values) - 1
# [2] While the window holds a position, look at its middle and the position after it. The middle is below hi, so the position after it exists.
while lo < hi:
mid = lo + (hi - lo) // 2
if values[mid] < values[mid + 1]:
# [3] Still climbing: a peak lies after mid, so lo moves past it.
lo = mid + 1
else:
# [4] Falling: mid may be a peak, so keep it: hi moves to it.
hi = mid
# [5] The window is empty, so lo == hi, and that position is a peak.
return lopublic int findPeak(int[] values) {
// [1] The window [lo, hi): the list climbs into lo, and hi is higher than the position after it, or is the last position, which is never compared.
int lo = 0;
int hi = values.length - 1;
// [2] While the window holds a position, look at its middle and the position after it. The middle is below hi, so the position after it exists.
while (lo < hi) {
int mid = lo + (hi - lo) / 2;
if (values[mid] < values[mid + 1]) {
// [3] Still climbing: a peak lies after mid, so lo moves past it.
lo = mid + 1;
} else {
// [4] Falling: mid may be a peak, so keep it: hi moves to it.
hi = mid;
}
}
// [5] The window is empty, so lo == hi, and that position is a peak.
return lo;
}int findPeak(vector<int>& values) {
// [1] The window [lo, hi): the list climbs into lo, and hi is higher than the position after it, or is the last position, which is never compared.
int lo = 0;
int hi = (int)values.size() - 1;
// [2] While the window holds a position, look at its middle and the position after it. The middle is below hi, so the position after it exists.
while (lo < hi) {
int mid = lo + (hi - lo) / 2;
if (values[mid] < values[mid + 1]) {
// [3] Still climbing: a peak lies after mid, so lo moves past it.
lo = mid + 1;
} else {
// [4] Falling: mid may be a peak, so keep it: hi moves to it.
hi = mid;
}
}
// [5] The window is empty, so lo == hi, and that position is a peak.
return lo;
}function findPeak(values) {
// [1] The window [lo, hi): the list climbs into lo, and hi is higher than the position after it, or is the last position, which is never compared.
let lo = 0;
let hi = values.length - 1;
// [2] While the window holds a position, look at its middle and the position after it. The middle is below hi, so the position after it exists.
while (lo < hi) {
const mid = lo + Math.floor((hi - lo) / 2);
if (values[mid] < values[mid + 1]) {
// [3] Still climbing: a peak lies after mid, so lo moves past it.
lo = mid + 1;
} else {
// [4] Falling: mid may be a peak, so keep it: hi moves to it.
hi = mid;
}
}
// [5] The window is empty, so lo == hi, and that position is a peak.
return lo;
}Dry run: A route with three high points: the search climbs to one of them. The step-by-step player loads in your browser.
A peak search compares the middle with the next position and walks toward the higher one, so it always ends on a peak, though not always the highest.
Exercise · Put it in order: Climb to a peak. Arrange the lines into a search that returns the position of a peak: a value higher than the values next to it. The outside counts as lower.
def find_peak(values):
lo = 0
hi = len(values) - 1
while lo < hi:
mid = lo + (hi - lo) // 2
if values[mid] < values[mid + 1]:
lo = mid + 1
else:
hi = mid
return lo
hi = mid - 1The search ended at position 1, the height 155. That is a peak, but it is not the highest one, which is 190 at position 5. Which peak you reach depends on the middles. A peak search promises a peak, not the highest.
For [112, 155, 121, 134, 118, 190, 127] the window starts as [0, 6), and position 3 holds 134 with 118 after it, so hi moves to 3. Position 1 holds 155 with 121 after it, so hi moves to 1. Position 0 holds 112 with 155 after it, so lo moves to 1. The search made 3 comparisons and ended at the peak 155.
On a list of 100,000 readings, the search needs at most 17 comparisons. The scan needs 100,000.
Exercise · Predict the output: Which peak does the search find?. The elevation list has three peaks: 9, 8 and 6 are each higher than both neighbours. The code runs the peak search, printing every middle it checks and then the position it ends on. What does it print?
values = [2, 5, 9, 4, 8, 3, 6, 1]
lo, hi = 0, len(values) - 1
mids = []
while lo < hi:
mid = lo + (hi - lo) // 2
mids.append(mid)
if values[mid] < values[mid + 1]:
lo = mid + 1
else:
hi = mid
print(*mids, lo)lo, hi and mid, so the extra space is O(1).Real production data brings edge cases.
Before the first write, values = []. The window is [0, 0), the loop never runs, and the break search returns 0. The search for an id returns -1, and the template checks for an empty list first, because it would read values[n - 1] otherwise.
For values = [10, 20, 30], every id is at most the last id, so the break search returns 0, and the first run is empty. An id above 30, such as 40, belongs to the first run, which is the empty window [0, 0), so the search returns -1 without reading anything.
For values = [2, 3, 4, 1], the second run has one id. The search ends with lo = 3. The id 4 is above the last id 1, so it is searched in positions 0 to 2, and it is found at position 2.
For values = [9, 4], the break is at position 1. For a peak search, [1, 2, 3, 4] returns 3, and [4, 3, 2, 1] returns 0, because the peak is at an end. For [7] the window is [0, 0) and the answer is 0.
Many interview answers search a rotated list without finding the break first. They rest on one fact: a window of a rotated list holds at most one break. So when the middle splits it, at least one half has no break and is sorted.
Which half? Compare the first id of the window with the middle id. If values[lo] <= values[mid], there is no break from lo to mid. A break there would put mid in the second run, below every id of the first run, values[lo] included.
Otherwise the break is between lo and mid, so the ids from mid to the last position of the window, hi - 1, come after it and are sorted.
Inside the sorted half a range check says whether x can be there. If it can, the window keeps that half, and otherwise it keeps the other half.
def search_one_pass(values, x):
lo, hi = 0, len(values)
while lo < hi:
mid = lo + (hi - lo) // 2
if values[mid] == x:
return mid
if values[lo] <= values[mid]:
# no break from lo to mid: that half is sorted
if values[lo] <= x < values[mid]:
hi = mid
else:
lo = mid + 1
else:
# the break is between lo and mid: mid to hi - 1 is sorted
if values[mid] < x <= values[hi - 1]:
lo = mid + 1
else:
hi = mid
return -1On the ring with x = 67, the middle is position 5, with 3. The first id, 62, is above 3, so the right half, 3 to 27, is sorted, and 67 is not in it: hi moves to 5. In [0, 5) the middle is position 2, with 71.
Now 62 is at most 71, so the left half is sorted, and 62 ≤ 67 < 71: hi moves to 2. In [0, 2) the middle is position 1, which holds 67.
It costs the same as the two searches, O(log n), and it is a fair interview answer. But it is not the first-true template. It has an equality exit and four cases, and each range check has a strict side and an inclusive side to get right. That is why this lesson finds the break first.
Exercise · Break it: Find the list that hides a value. This one-pass search asks whether x is in a list that is a sorted list rotated by some amount. Repeats are allowed. Find a rotated list and an x where it says no, although x is in the list.
def contains(values, x):
lo, hi = 0, len(values)
while lo < hi:
mid = lo + (hi - lo) // 2
if values[mid] == x:
return True
if values[lo] <= values[mid]:
if values[lo] <= x < values[mid]:
hi = mid
else:
lo = mid + 1
else:
if values[mid] < x <= values[hi - 1]:
lo = mid + 1
else:
hi = mid
return FalseAll the ids so far were different. Real ids can repeat, and a repeat can hide the break. Take [1, 1, 1, 0, 1], a rotation of the sorted list [0, 1, 1, 1, 1]. The last id is 1 and every id is at most 1, so the break search returns 0, but the smallest id, 0, is at position 3.
The rule "above the last id means first run" fails when the first run holds ids equal to the last id. There is a repair: drop the tail that equals the first id, and then search. For the smallest value it takes a few lines:
def smallest_with_repeats(values):
end = len(values)
# drop the tail that equals the first id: it cannot tell the two runs apart
while end > 1 and values[end - 1] == values[0]:
end -= 1
lo, hi = 0, end
while lo < hi:
mid = lo + (hi - lo) // 2
if values[mid] > values[end - 1]:
lo = mid + 1
else:
hi = mid
return values[lo]On [1, 1, 1, 0, 1] it drops the last 1, searches [1, 1, 1, 0] and returns 0. But the first loop costs one step for every id it drops. For 100,000 ids with a single 0 at position 1, [1, 0, 1, 1, ..., 1], it drops 99,998 ids.
That is a limit of the problem, not a weakness of this code. Take a list of n ones. Put one 0 in it, in any place, and the list is still a rotation of a sorted list. There are n such lists, and the list with no 0 is valid too.
Suppose a search reads positions and finds only ones. If it stops before it has read all n positions, it cannot tell whether the 0 sits in a position it has not read. So in the worst case every position must be read, and the worst case is O(n).
The one-pass search breaks on repeats too. On [1, 0, 1, 1, 1] with x = 0, the first id and the middle id are both 1, so the test says that the left half is sorted. The 0 is not in the range 1 to 1, so the search drops the left half, with the 0 in it, and returns -1.
The usual repair skips one equal id at each end when the first, middle and last ids are equal. On a list of ones with a single 0, that again reads every position in the worst case.
With few repeats the search is still fast. The cost grows with the number of ids at the end that equal the first id.
This version runs the lower bound from the last lesson on the whole ring. It assumes that the list is sorted.
Counterexample: values = [62, 67, 71, 75, 80, 3, 8, 14, 21, 27] and x = 67. The search looks at position 5, sees 3, which is below 67, and moves right. It ends at position 10, the end of the list, and reports that 67 is missing, but it is at position 1. For x = 14 the same code works, which is why the bug can pass a few tests.
A common mistake: running the usual binary search on a rotated list. It can say that an id is missing when it is in the list.
This version tests values[mid] >= values[0] to decide that mid is in the first run. It works on a rotated list, but on a list that was never rotated every id is at least the first id.
Counterexample: values = [10, 20, 30, 40, 50]. Every test is true, so lo keeps moving and the search ends at position 5, past the end of the list. The correct answer is 0. Comparing with the last id has no such problem, because the last id is in the second run, or the list has only one run.
This version uses Template 1 on a list with repeats. The test values[mid] > values[n - 1] says that no id is in the first run when the first run holds ids equal to the last id.
Counterexample: values = [1, 1, 1, 0, 1]. Every id is at most the last id, 1, so the search returns 0. The smallest id is 0, at position 3.
A common mistake: ignoring repeats. When the first run holds ids equal to the last id, the test cannot tell the two runs apart.
This version runs the peak search on a list that has equal neighbours. When the middle equals the next id, the test values[mid] < values[mid + 1] is false, so the search moves hi to mid.
Counterexample: values = [1, 2, 2, 3]. The middle is position 1, with 2, and the next id is also 2, so hi moves to 1. Then lo moves to 1, and the search returns position 1, whose neighbours are 1 and 2. That is not a peak, because the only peak is the 3 at position 3.
Your team lead hands you a list that was merged from several sorted pieces: [5, 6, 1, 2, 7, 8, 3, 4]. It has three sorted runs and two breaks. You search for the id 2, which is at position 3.
The last id is 4. The break search checks position 4, with 7, which is above 4, so lo moves to 5. It ends at position 6 and takes the id 3 as the start of the second run. The id 2 is at most 4, so the search looks in positions 6 and 7 and reports -1.
The answer is wrong. The test "above the last id" is not false and then true on this list. Sort the list, or search each run on its own.
Your team lead brings four product changes. Each one asks which shape the list has.
A support tool wants the slot of the oldest id, and by how many slots the sorted list was rotated. For distinct ids, both answers are the position of the smallest id. That is Template 1 (LeetCode 153: Find Minimum in Rotated Sorted Array).
Many interview answers search a rotated list in one pass, by asking which half of the window is sorted, as shown above. It costs the same, O(log n), but it has more cases to get right (LeetCode 33: Search in Rotated Sorted Array).
Sensor timestamps repeat. With repeats, the smallest value and the search both need the repair above, and the worst case is O(n). Say so out loud in an interview (LeetCode 154: Find Minimum in Rotated Sorted Array II and LeetCode 81: Search in Rotated Sorted Array II).
A streaming app records its live audience each minute. It grows to one peak, and then it only falls. To find a given size, find the peak first with Template 3, and search the rising part with the lower bound. On the falling part, use the same loop with the test turned round, so lo moves past a value above the target (LeetCode 1095: Find in Mountain Array).
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 oldest id of a ring buffer without reading the ring. Then explain how you search it for an id. 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.
A ring that wrapped is a rotated sorted list: two sorted runs, where every id in the first run is above every id in the second.
I compare the middle with the last id. Above it means the first run, and at most it means the second run. That flips once, so the first-true search finds where the second run starts, which is the smallest id.
To find an id, I pick the run with the last id, and run the lower bound inside it. With repeats the worst case is O(n), and I say so.
A rotated sorted list has two sorted runs. The ids in the first run are all above the last id, and the ids in the second run are all at most the last id.
That test flips once, so I use the first-true template to find where the second run starts. That position holds the smallest id, and it is 0 when the list is not rotated. It takes log n steps.
To search for a value, I compare it with the last id to choose the run, and then I run the lower bound inside that run.
For a peak, I compare the middle with the next value. If the list climbs, I move lo past the middle. Otherwise I move hi to it. The window always holds a peak, but not always the highest one.
Repeats can hide the break, and then the worst case is linear. Neighbours that are equal break the peak search.
Checkpoint · The rotated list
Q1/3 The list is [62, 67, 71, 75, 80, 3, 8, 14, 21, 27]. Where does the second run start?
Answer: B
The first run is 62 to 80, and the second run starts at the id 3, which is position 5. Position 4 holds the largest id, the last id of the first run.
Q2/3 Which test says that the id at mid is in the first run of a rotated list?
Answer: B
Every id in the first run is above the last id of the list, and every id in the second run is at most the last id. That test is false and then true, so the first-true template can use it.
Q3/3 A list was never rotated: [10, 20, 30]. What does the search for the start of the second run return?
Answer: A
Every id is at most the last id, so no id is in the first run, and hi keeps moving down to 0. The smallest id is the first one.
Checkpoint · Searching a rotated list
Q1/3 You search the list [62, 67, 71, 75, 80, 3, 8, 14, 21, 27] for the id 67. Which run does the search use?
Answer: A
An id above the last id can only be in the first run. The first run holds the positions 0 to 4, and 67 is at position 1.
Q2/3 Why does the lower bound from the last lesson fail on the ring [62, 67, 71, 75, 80, 3, 8, 14, 21, 27]?
Answer: C
The ring has a break. For the id 67 the search looks at the id 3, moves right, and ends at the end of the list, so it reports that 67 is missing. It is at position 1.
Q3/3 The list is [2, 3, 4, 1] and you look for the id 3. In which positions does the search look for it?
Answer: A
The last id is 1, and 3 is above it, so 3 can only be in the first run. The second run starts at position 3, so the first run is positions 0 to 2.
Checkpoint · Peaks and repeats
Q1/4 In a peak search the middle holds 30 and the next position holds 26. What does the search do?
Answer: B
The list falls after mid, so mid may be a peak, or a peak lies before it. Keep it in the window, with hi = mid. A rising pair would move lo to mid + 1.
Q2/4 Why does the peak search start with hi = n - 1 and not hi = n?
Answer: C
The last position is a possible answer, but it is never compared. With hi = n, mid could reach n - 1 and read values[n], which does not exist.
Q3/4 The peak search on [112, 155, 121, 134, 118, 190, 127] returns position 1, the height 155. What does this show?
Answer: C
Position 1 is higher than both its neighbours, so it is a peak. The search promises a peak. Which one it reaches depends on the middles.
Q4/4 What is the worst-case cost of finding the smallest value in a rotated list that can hold repeats?
Answer: C
A list of ones with one 0 in it looks the same until you read the place that holds the 0, so in the worst case every position must be read.
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 | Lowest reading in a rotated list | Monitoring | Medium | The start of the second run, inside a range of slots |
| 2 | Find a code in a rotated shard list | Platform | Medium | The break, then a search in the right run |
| 3 | Peak of the load curve | Monitoring | Medium | The peak search on a new curve for every price, with ties |
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.