Sorting, then binary search on the answer
- Sort with sorted or list.sort, choose what to compare with a key function or a tuple key, and say what a stable sort promises and what a sort costs, with comparison counts to back it
- Write a binary search by hand, with two bounds that each keep a promise, a middle that keeps the loop moving, and the right answer at both edges
- Answer how many are smaller, the latest at or before, and how many fall in a range with bisect_left and bisect_right, and say why insort is O(n)
- Look up what a key held at any moment from each key's sorted times, with late changes, deletes the past remembers, and snapshots that copy nothing
- Spot a yes or no test that flips once as a number grows, and binary search the number instead of the data
- Answer the follow-ups: data too big to sort in memory, the k-th item without a full sort, a rotated sorted list, real numbers to a tolerance, and a list kept sorted while it changes
A store that remembers every change, the way the coding round asks
Time Based Key-Value Store is on OpenAI's and Netflix's LeetCode tag lists (2 sources), Snapshot Array is on OpenAI's (1 source), and two OpenAI candidates report a coding round in parts on a social graph with snapshots (2 reports). This lesson's practice problem is that shape, a configuration store, in three levels:
ConfigStorewithset(key, value, time)andget(key, time): the value of the latest change at or before a moment, in O(log n).- Late changes that take their place in time,
delete(key, time), andchanges(key, start, end), a count from start up to end.snapshot()andget_snapshot(key, snap), without copying the store.
Call, after changes at 100 and 160 Returns get("timeout", 159.5)the value set at 100 get("timeout", 99)None: nothing at or before 99 get("timeout", 160)the value set at 160: a read at a change sees it changes("timeout", 100, 160)1: the start counts, the end doesn't
The lesson builds it from the bottom: sorting, binary search by hand, the bisect module, versions, and binary search on the answer. 23 steps end with a small task in the editor.
Sort once, and the questions get easy
Many coding questions are hard on data in the order it arrived, and easy on the same data sorted. After a sort, copies sit next to each other. Overlapping time windows sit next to each other. And the question every lookup asks, where does this value fall, takes about 20 looks on a million sorted items instead of a million.
times = [160, 100, 220]
print(sorted(times))
print(times)
[100, 160, 220]
[160, 100, 220]
sorted(times) built a new list. times itself didn't change.
result = times.sort()
print(result)
print(times)
result = times.sort(). What's in result?
A key function picks what to compare, and a tuple key compares field by field
Here's a change log for a configuration store, in the order the changes arrived. Each entry is (key, time, value). To put it in time order, compare only the time:
changes = [
("timeout", 160, 45),
("retries", 120, 5),
("timeout", 100, 30),
# same time as the line above, arrived later
("retries", 120, 3),
("timeout", 220, 60),
]
for change in sorted(changes, key=lambda c: c[1]):
print(change)
('timeout', 100, 30)
('retries', 120, 5)
('retries', 120, 3)
('timeout', 160, 45)
('timeout', 220, 60)
A key function maps each item to the thing to compare. Here it's the time, c[1].
Python calls the key once per item, not once per comparison. A key that counted its calls confirmed it: 10,000 calls to sort 10,000 items.
For more than one field, return a tuple. By key, then time:
for change in sorted(changes, key=lambda c: (c[0], c[1])):
print(change)
('retries', 120, 5)
('retries', 120, 3)
('timeout', 100, 30)
('timeout', 160, 45)
('timeout', 220, 60)
Two tuples compare their first fields. They look at the second field only when the first fields tie:
| Compared | First fields | Then |
|---|---|---|
('retries', 120) and ('timeout', 100) | 'retries' is smaller | done |
('timeout', 100) and ('timeout', 160) | a tie | 100 < 160: done |
('retries', 120) and ('retries', 120) | a tie | a tie: equal keys |
The last row is two different changes with equal keys. The next section says which of them comes first.
To sort one field the other way, negate it when it's a number. Each key's newest change first is key=lambda c: (c[0], -c[1]), which puts timeout at 220, 160, 100. A string can't be negated. For a string, sort twice: the next step, on stable sorts, shows how.
In the editor, write newest_first(changes). It prints the log with the keys from A to Z, and each key's newest change first.
Python's sort is stable: items with equal keys keep their original order
Look again at the two retries changes at 120. In the sort by time and in the sort by key and time, they stayed in arrival order: 5, then 3. That's a promise, not luck. Python's sort is stable: when several items have equal keys, they keep the order they had before the sort.
Now sort the log with no key at all:
for change in sorted(changes):
print(change)
('retries', 120, 3)
('retries', 120, 5)
('timeout', 100, 30)
('timeout', 160, 45)
('timeout', 220, 60)
With no key, the key is the whole tuple. When the name and the time tie, the value decides, so 3 now comes before 5.
A store that sorted this way would believe 5 was the later write. And with values that don't support <, it doesn't even run:
sorted([("limits", 5, {"cpu": 2}), ("limits", 5, {"cpu": 4})])
TypeError: '<' not supported between instances of 'dict' and 'dict'
Sort by the fields you mean, and let stability handle the ties. In the practice problem, two changes at the same time go to the one made later. A stable sort by time leaves the later one second.
reverse=True keeps the promise too. Items with equal keys still keep their original order. They are not flipped:
for change in sorted(changes, key=lambda c: c[1], reverse=True):
print(change)
('timeout', 220, 60)
('timeout', 160, 45)
('retries', 120, 5)
('retries', 120, 3)
('timeout', 100, 30)
Stability also lets you sort two fields in opposite directions when you can't negate one. Sort twice: first by the second field, then by the first. Pass reverse=True to the pass whose field goes the other way. The second sort keeps the first sort's order inside each group of equal keys. Here are the names from Z to A, with each name's changes oldest first:
by_time = sorted(changes, key=lambda c: c[1])
for change in sorted(by_time, key=lambda c: c[0], reverse=True):
print(change)
('timeout', 100, 30)
('timeout', 160, 45)
('timeout', 220, 60)
('retries', 120, 5)
('retries', 120, 3)
In the editor, write timelines(changes), with a sort that keeps ties in arrival order. It prints the log's timelines.
What a sort costs
Every sort compares items, and counting the comparisons shows what it costs.
Python's sort is Timsort. It finds stretches that are already in order, called runs, and merges them. Here are its comparisons, counted with a class whose __lt__ adds one per call:
Timsort counted 999 comparisons on 1,000 items that were already sorted. About how many on 1,000 in random order?
A sort that only compares items can't beat log2(n!) comparisons in its worst case
No sort that compares items can do much better than that.
A sort that only compares: in its worst case, how many comparisons must it make on 3 items?
Counting sort on 7 values, each from 0 to 5. How many times does it compare two items?
On a million floats a sort costs about 25 passes over them, so sort once
In time, on random floats:
| n | sorted(d) | Per item | sorted of already sorted data | min(d), one pass |
|---|---|---|---|---|
| 10,000 | 0.84 ms | 84 ns | 0.04 ms | 0.06 ms |
| 100,000 | 11.24 ms | 112 ns | 0.44 ms | 0.62 ms |
| 1,000,000 | 152.23 ms | 152 ns | 21.30 ms | 5.96 ms |
Python 3.12, best of 5 runs with timeit, on the laptop these numbers come from.
The time per item grows with n, roughly as the in the cost predicts. The comparison counts from the step on what a sort costs are the cleaner evidence.
The jump for sorted data at a million is memory, not comparisons. In a separate run, just copying the list went from 0.21 ms at 100,000 items to 8.13 ms at a million.
A sort is 25 times one pass over a million items. So sort once and reuse the order. Never sort inside a loop.
Memory, measured with tracemalloc on a million floats: sorted(d) peaked at 11.44 MiB. That's 8 MB for the new list of pointers, plus scratch space for merging runs. d.sort() peaked at 3.81 MiB, the scratch space alone.
Sorted data puts related items next to each other
Sorting puts copies side by side.
items = [42, 7, 19, 7, 3]
s = sorted(items)
print(s)
print(any(a == b for a, b in zip(s, s[1:])))
[3, 7, 7, 19, 42]
True
zip(s, s[1:]) pairs each item with the one after it, so the check only looks at neighbors.
The hash-maps lesson's seen-set finds a repeat in O(n) time and O(n) memory. Sorting in place costs O(n log n) time but needs no set, only the sort's scratch space. That's the trade an interviewer asks about when memory is tight. Contains Duplicate is on Netflix's tag list (1 source).
Sorted data helps with pairs too. With one pointer at each end of a sorted list, one pass finds two values that add up to a target. The sliding-window lesson builds that.
In the editor, write smallest_gap(times): the two changes closest in time. It prints the gap for five times, then for one.
Sorted by start, a window can only overlap the merged window just before it
Merge Intervals is on Netflix's tag list too (1 source). A service has maintenance windows, (start, end) in hours, and you want the hours it's down:
windows = [(14, 16), (1, 3), (8, 10), (2, 6), (15, 18), (9, 12), (3, 5)]
print(merge(windows))
Windows (14, 16), (1, 3), (8, 10), (2, 6), (15, 18), (9, 12) and (3, 5), merged where they overlap. How many are left?
Two bounds keep two promises, and each look moves one of them past the middle
Here are the times a setting changed, sorted. An incident started at 250. How many changes came before it, and which change came next?
Both answers are one index: the first position whose time is at least 250. A scan from the left looks at every time up to it, O(n). Binary search uses the order to throw away half of what's left with each look:
def first_at_or_after(times, target):
lo, hi = 0, len(times)
while lo < hi:
mid = (lo + hi) // 2
if times[mid] < target:
# mid and everything before it are below the target
lo = mid + 1
else:
# mid and everything after it are at least the target
hi = mid
return lo
times = [100, 130, 160, 220, 300, 410, 520, 600]
print(first_at_or_after(times, 250))
8 sorted times, and the target is 250. How many looks does binary search take to find the first time at or after it?
The answer can be 0 or len(times), so hi starts at len(times)
Both edges come out right, with no special case.
print(first_at_or_after(times, 50))
print(first_at_or_after(times, 700))
0
8
The answer is a place between items, not an item. Eight times have nine such places:
| Target | Answer | The place |
|---|---|---|
| 50 | 0 | before every time |
| 250 | 4 | between 220 and 300 |
| 700 | 8 | after every time: len(times) |
Target 50 returns 0: nothing is below it. Target 700 returns 8, which is len(times): everything is below it, and there's no next change. Neither edge needs a special case.
That's why hi starts at len(times) and not at the last index. Start it at len(times) - 1 and the loop can never return 8.
Each look at least halves the range, so a million items take at most 20 looks
While lo < hi, the middle (lo + hi) // 2 is at least lo and less than hi. So lo = mid + 1 moves lo up by at least one, and hi = mid moves hi down by at least one. Each look cuts the unsettled range at least in half.
That's at most looks: log base 2 of n, rounded down, plus one. Measured by running the loop to every boundary: 4 looks for 8 items, 10 for 1,000, 20 for a million, 30 for a billion.
On a million sorted integers, finding a target past the end:
The loop by hand is about 20,000 times faster than the scan. bisect runs the same loop in C, for another factor of 8.
In the editor, write max_looks(n). It prints the most looks for 8 items, a thousand, a million and a billion.
In Java, C and C++, (lo + hi) / 2 can overflow
In Python, (lo + hi) // 2 is safe, because Python's integers don't overflow. In Java, C and C++ they do. That line sat as a real bug in the JDK's own binary search for about nine years. Its author explains that it fails when lo + hi is bigger than the largest positive int.
In those languages, write lo + (hi - lo) / 2. An interviewer who works in one may ask why you didn't.
In the editor, write the loop in last_at_or_before(times, t). It prints the latest change at or before 250, before 99, and at 160.
bisect_left lands before the values equal to x, bisect_right after them
You'll rarely write that loop in Python. The bisect module has it, written in C. Its two searches differ only in what they do with values equal to the one you search for:
from bisect import bisect_left, bisect_right
times = [100, 130, 130, 130, 220, 300]
print(bisect_left(times, 130), bisect_right(times, 130))
print(bisect_left(times, 200), bisect_right(times, 200))
1 4
4 4
Each returns the place where x would go to keep the list sorted, and the answer is how many items sit to its left:
| Call | Returns | The place |
|---|---|---|
bisect_left(times, 130) | 1 | before every 130 |
bisect_right(times, 130) | 4 | after every 130 |
bisect_left(times, 200) | 4 | between the 130s and 220 |
bisect_right(times, 200) | 4 | the same, since no time is 200 |
bisect_left is the loop you wrote first. It returns the first index whose value is at least x. Everything before that index is below x, and everything from it on is at least x.
bisect_right returns the first index whose value is greater than x, so it goes past every copy of x. It's the loop from the last_at_or_before checkpoint, before its - 1.
When x isn't in the list, as with 200, the two agree.
Both also take lo and hi, to search only part of the list. bisect_left(a, x, lo, hi) looks only at a[lo:hi], and its answer is still an index into all of a:
print(bisect_left(times, 220, 3, 6))
print(bisect_left(times[3:6], 220))
4
1
The slice answers 1, a place in the copy, and making that copy cost O(n) before the search even started. To search part of a list, don't slice it. Pass lo and hi.
In the editor, write count_equal(times, x): how many changes happened exactly at x. It prints the count at 130 and at 200.
Read an insertion point as a count, and most lookups take one line
The name says where you'd insert x. Read it instead as a count. The table uses a half-open range, written [start, end): it includes its start and leaves out its end. That's the usual way to state a time range. [start, end] includes both ends. Its last column runs each line on a = [100, 130, 130, 130, 220, 300], with x = 130, a range from 130 to 300, and 200 for the last row.
| Question | Expression | Result |
|---|---|---|
| How many are less than x | bisect_left(a, x) | 1 |
| How many are at most x | bisect_right(a, x) | 4 |
| The latest at or before x | a[bisect_right(a, x) - 1] | 130, index 3 |
| The latest strictly before x | a[bisect_left(a, x) - 1] | 100, index 0 |
| The earliest at or after x | a[bisect_left(a, x)] | 130, index 1 |
How many in [start, end) | bisect_left(a, end) - bisect_left(a, start) | 4 |
How many in [start, end] | bisect_right(a, end) - bisect_left(a, start) | 5 |
| Is x there | i = bisect_left(a, x), then i < len(a) and a[i] == x | False |
Pick the pair by asking what a value equal to an end should do. The half-open range uses bisect_left at both ends:
| Range | Bounds | Count |
|---|---|---|
[130, 300): 130 counts, 300 doesn't | bisect_left at both ends: 1 and 5 | 5 - 1 = 4 |
[130, 300]: both ends count | bisect_right at the end: 1 and 6 | 6 - 1 = 5 |
The three lookups that index into the list need an edge check every time: the index must be at least 0 and below len(a). Subtracting 1 can give -1, and the earliest at or after can be len(a), one past the last index.
In the editor, write changes_between(times, start, end), a count over a half-open range. It prints the changes from 130 up to 200, and a range that ends before it starts.
With key=, pass the field you search for, not a whole record
Since Python 3.10, every bisect function takes key=, so you can search a list of records by one field. The search applies the key to the list's items, but not to the value you search for. So pass the field, not a record:
history = [(100, "a"), (130, "b"), (130, "c"), (220, "d")]
i = bisect_right(history, 130, key=lambda change: change[0])
print(i, history[i - 1])
3 (130, 'c')
Pass (130,) there instead, and it fails with TypeError: '<' not supported between instances of 'tuple' and 'int'.
In the editor, write value_at(history, t) with bisect_right and key=. It reads a history at five times.
insort finds the spot in O(log n), then shifts everything after it in O(n)
Finding the spot is cheap. Making room isn't.
insort(a, 140) on a = [100, 130, 160, 220, 300]. How many items move to make room?
A read at time t wants the latest change at or before t
The practice problem starts with a store where set(key, value, time) records a change and get(key, time) returns what the key held at that moment.
timeout changed to 30 at time 100, 45 at 160 and 60 at 220. What does get(159.5) return?
Each key keeps its times and values in two lists, searched with bisect_right
Each key gets its changes in time order, as two lists: the times, and the values at the same positions. With the times in a list of their own, bisect searches plain numbers. It needs no key function, and no tuples that compare values on a tie.
from bisect import bisect_right
# a marker that can't be equal to any real value
DELETED = object()
class Versions:
def __init__(self):
# key -> its change times, sorted
self.times = {}
# key -> the value at the same position
self.values = {}
def set(self, key, value, time):
times = self.times.setdefault(key, [])
values = self.values.setdefault(key, [])
# after any change at the same time
i = bisect_right(times, time)
times.insert(i, time)
values.insert(i, value)
def delete(self, key, time):
self.set(key, DELETED, time)
def get(self, key, time):
times = self.times.get(key, [])
# how many changes are at or before time
i = bisect_right(times, time)
if i == 0:
return None
value = self.values[key][i - 1]
return None if value is DELETED else value
store = Versions()
store.set("timeout", 30, 100)
store.set("timeout", 45, 160)
store.set("timeout", 60, 220)
print([store.get("timeout", t) for t in (99, 100, 159.5, 160, 219, 220, 10**9)])
[None, 30, 30, 45, 45, 60, 60]
bisect_right answers an edge in each place it's used:
- A read exactly at a change sees it.
bisect_right(times, time)counts the changes at or beforetime, so a read at 160 counts the change at 160. Withbisect_left, a read at 160 would still see 30. - Two changes at the same time go to the later call.
bisect_rightinserts the new change after the old one, and a read takes the last change it counts.
Here is a tie:
store.set("mode", "z-old", 100)
store.set("mode", "a-new", 100)
print(store.times["mode"], store.values["mode"], store.get("mode", 100))
[100, 100] ['z-old', 'a-new'] a-new
A late change takes its place in time, and shifts what comes after it
Changes can arrive late, from a replica that caught up.
store.set("timeout", 40, 130)
print(store.times["timeout"])
print(store.values["timeout"])
print([store.get("timeout", t) for t in (129, 130, 159)])
[100, 130, 160, 220]
[30, 40, 45, 60]
[30, 40, 40]
The change at 130 arrived after the one at 220, and it still landed between 100 and 160. Both lists insert at the same index, so each value stays next to its time.
When times arrive in order, i is the end of the list and nothing shifts. A late change shifts everything after it: O(n), the same cost as insort.
A late change also rewrites past answers. Before it arrived, a read at 140 returned 30. Now it returns 40. Every read from 130 up to the next change, at 160, gets a new answer, so a cache that kept any of those answers now holds stale ones.
In the editor, write stale_reads(times, time). It finds the reads that a late change at 130, a tie at 160 and a change after the last one make stale.
A delete records a marker, so earlier times still answer
A delete hides a key from its time on, and only from then.
store.delete("timeout", 250)
print([store.get("timeout", t) for t in (200, 249, 250, 300)])
After delete at 250, what do get at 200, 249, 250 and 300 return?
A snapshot only adds 1 to a counter
The practice problem's last level adds snapshots. snapshot() saves the store as it stands and returns a number, and a read names that number. Snapshot Array, on OpenAI's tag list (1 source), is this level with array positions for keys and no times.
The obvious version copies every key at each snapshot. That's O(k) time and memory per snapshot for k keys, even when only one key changed since the last one.
set 30, snapshot, set 45, set 60, snapshot, snapshot, set 90. What does snapshot 1 read?
A read at snapshot s takes the key's last change with a count of at most s
Each key keeps two lists: the counts its changes recorded, and the values. A second set at the same count replaces the value, since no snapshot saw the first one. Here are the key's lists after each call from the last step:
| Call | counts | values |
|---|---|---|
| set 30 | [0] | [30] |
| snapshot 0 | no change | no change |
| set 45 | [0, 1] | [30, 45] |
| set 60 | [0, 1] | [30, 60] |
| snapshot 1 | no change | no change |
| snapshot 2 | no change | no change |
| set 90 | [0, 1, 3] | [30, 60, 90] |
set 60 has the same count as set 45, so it replaces 45.
To read the key at snapshot s, take its last change with a count of at most s: position bisect_right(counts, s) - 1. It's the same search as before, on a counter instead of a clock.
Snapshot 0 reads position bisect_right([0, 1, 3], 0) - 1 = 0, which is 30. Snapshots 1 and 2 both read position 1, which is 60. Nothing changed between them, and nothing had to be stored for snapshot 2. A snapshot costs O(1), and a read O(log c) for a key with c changes.
In the editor, write get(key, snap) for the SnapshotStore. It reads the table's three snapshots.
The LeetCode version of the practice problem's first level, Time Based Key-Value Store, solved and coded in Python.
When a yes-or-no test flips once as a number grows, binary search the number
So far the search ran over data. Sometimes the sorted thing is the answer itself. Koko Eating Bananas is on Netflix's tag list (1 source), and one Netflix candidate reports an easy binary search question in a phone screen (1 report). Here's that shape in a log pipeline.
A job has five batches of log files, with sizes [30, 11, 23, 4, 20]. A worker processes up to rate files an hour, from one batch at a time. An hour on a batch with fewer than rate files left finishes that batch, and the rest of the hour goes unused. What's the slowest rate that finishes everything within 6 hours?
Batches of 30, 11, 23, 4 and 20 files, and the job must finish in 6 hours. What's the slowest rate that does it?
The search is the same loop, with hours(mid) <= h as the test
With hours written, the search is the loop from before.
def hours(rate, batches):
# ceil(b / rate) in integers
return sum(-(-b // rate) for b in batches)
def slowest_rate(batches, h):
# at max(batches), every batch takes one hour
lo, hi = 1, max(batches)
while lo < hi:
mid = (lo + hi) // 2
# fast enough: the answer is mid or slower
if hours(mid, batches) <= h:
hi = mid
# too slow: the answer is faster than mid
else:
lo = mid + 1
return lo
print(slowest_rate([30, 11, 23, 4, 20], 6))
23
It's the loop you wrote by hand, with hours(mid) <= h in place of times[mid] >= target. Here are its looks with h = 6:
lo | hi | mid | hours(mid) | move |
|---|---|---|---|---|
| 1 | 30 | 15 | 8 | too slow: lo = 16 |
| 16 | 30 | 23 | 6 | fast enough: hi = 23 |
| 16 | 23 | 19 | 8 | too slow: lo = 20 |
| 20 | 23 | 21 | 7 | too slow: lo = 22 |
| 22 | 23 | 22 | 7 | too slow: lo = 23 |
Five calls to hours found 23. Trying 1, 2, 3 and up takes 23 calls.
The bounds are part of the answer. hi = max(batches) is a rate that surely works, as long as h is at least the number of batches. If it isn't, no rate works, and that's the clarifying question to ask.
Each call to hours is O(n) for n batches, so the search costs O(n log m) for a largest batch of m. On 1,000 batches of up to 10,000 files with 1,500 hours, counting up from 1 called hours 5,082 times and took 207.6 ms. The binary search called it 13 times and took 0.60 ms.
Since Python 3.10, bisect can run this search for you, because False sorts before True. bisect_left(range(1, max(batches) + 1), True, key=lambda rate: hours(rate, batches) <= 6) + 1 returned 23. In an interview, the written loop is clearer.
In the editor, write least_capacity(weights, d) with the same search. It prints the least capacity that ships eight packages in three days.
The reported question this section's batches are modeled on, Koko Eating Bananas, solved with a binary search and coded in Python.
A worked example: the most pay from jobs that can't overlap
Maximum Profit in Job Scheduling is on Airbnb's LeetCode tag lists: the all-time, six-month and three-month ones (3 sources). In our setting, one GPU runs render jobs, one at a time. Each job has a start hour, an end hour and what it pays. A job can start at the hour another ends. Pick the jobs that pay the most in total.
jobs = [(1, 5, 70), (9, 14, 100), (0, 4, 60), (6, 11, 20), (4, 6, 40), (7, 10, 30)]
Jobs (start, end, pay): (0, 4, 60), (1, 5, 70), (4, 6, 40), (7, 10, 30), (6, 11, 20), (9, 14, 100), no two at once. What's the most pay?
A table of best totals: take each job or skip it
Before the real jobs, try the idea on an easy case. Five jobs run back to back: (0, 2), (1, 3), (2, 4), (3, 5) and (4, 6). Each overlaps only the job just before it and the job just after it. They pay 40, 70, 40, 30 and 50.
Let best[i] be the most pay from the first i jobs alone. best[0] is 0: no jobs, no pay. For job i there are two choices:
- Skip it, and the best stays
best[i]. - Take it, and job
i - 1can't run, but every job before that can. So the pay adds tobest[i - 1]. Job 0 has nothing before it, so its pay adds to 0.
The larger of the two is best[i + 1]:
i | Pay | Skip | Take | Best |
|---|---|---|---|---|
| 0 | 40 | 0 | 40 + 0 = 40 | 40 |
| 1 | 70 | 40 | 70 + 0 = 70 | 70 |
| 2 | 40 | 70 | 40 + 40 = 80 | 80 |
| 3 | 30 | 80 | 30 + 70 = 100 | 100 |
| 4 | 50 | 100 | 50 + 80 = 130 | 130 |
The answer is the last entry, 130: jobs 0, 2 and 4. Grabbing the 70 first blocks both its neighbors, and the best you can do around it is 120.
Each entry of best is built from earlier ones. That makes this a dynamic program: a table filled in an order where every entry's inputs are ready.
In the editor, write most_pay_in_a_row(pays). It fills the table for the five jobs.
Sorted by end time, bisect_right counts the jobs that can still run
Back to the render jobs. Sort them by end time and fill the same table in that order. Skipping job i still leaves best[i]. Taking it now adds its pay to best[j], where j counts the jobs that can run before it: the ones that end at or before its start.
The ends are sorted, so those jobs are a prefix of the list, and its length is bisect_right(ends, start). That's the latest at or before, again. In the warm-up, j was always i - 1. Here a search finds it.
jobs = [(1, 5, 70), (9, 14, 100), (0, 4, 60), (6, 11, 20), (4, 6, 40), (7, 10, 30)]
print(most_pay(jobs))
200
Every job that ends at or before start also ends before this job's own end, since start < end. So j never counts this job or a later one.
Trace it with ends = [4, 5, 6, 10, 11, 14], one row per job in end order. Skip is best[i], take is the pay plus best[j], and the larger is best[i + 1]:
Job i | j | Skip | Take | Best |
|---|---|---|---|---|
| (0, 4, 60) | 0 | 0 | 60 + 0 | 60 |
| (1, 5, 70) | 0 | 60 | 70 + 0 | 70 |
| (4, 6, 40) | 1 | 70 | 40 + 60 | 100 |
| (7, 10, 30) | 3 | 100 | 30 + 100 | 130 |
| (6, 11, 20) | 3 | 130 | 20 + 100 | 130 |
| (9, 14, 100) | 3 | 130 | 100 + 100 | 200 |
The row for (4, 6, 40) is where the clarification pays off. bisect_right(ends, 4) is 1, so the job that ends at 4 counts as done in time. With bisect_left it would be 0, and the function returns 170.
Test it against the subsets. On 300 random lists of up to 9 jobs, most_pay matched the best subset every time.
Give the cost. The sort is O(n log n), and each job does one binary search, so it's O(n log n) time and O(n) memory. It took 0.3 ms for 1,000 jobs, 3.6 ms for 10,000 and 46.2 ms for 100,000.
In the editor, write most_pay(jobs), the function the code above calls. It prints the most pay from the six render jobs.
What if the data is too big to sort in memory?
Sort it in pieces. Read as much as fits, sort it, and write it to disk as a sorted run. Repeat until the input runs out. Then merge the runs, which only ever needs the front of each one:
heapq.merge(*runs) takes sorted inputs and hands out one sorted stream, holding only the front item of each input. It doesn't pull all the data into memory at once.
import heapq
import itertools
import tempfile
def external_sort(numbers, chunk):
runs = []
numbers = iter(numbers)
while batch := list(itertools.islice(numbers, chunk)):
batch.sort()
run = tempfile.TemporaryFile("w+")
run.writelines(f"{x}\n" for x in batch)
run.seek(0)
runs.append(run)
return heapq.merge(*((int(line) for line in run) for run in runs))
On a million random integers in chunks of 100,000, ten runs, the output came out in order, and the traced memory peaked at 6.92 MiB. sorted() of the same numbers in memory peaked at 34.76 MiB.
Every number is written once and read back once. With more runs than you can keep open, merge them in rounds. The next lesson, on heaps, builds that merge itself.
How do you find the k-th smallest without a full sort?
If the data is sorted, it's a[k - 1]. If not, a full sort is O(n log n), and you don't need it:
- Quickselect splits the data around a pivot and keeps only the side that holds position k. That's O(n) on average.
- A heap of size k keeps the k smallest seen so far in one pass. A heap finds its top item at once and adds or removes one in O(log k), so the pass is O(n log k), which wins when k is small.
The next lesson, on heaps, builds both and measures where each wins. Its worked example finds the k-th smallest in a sorted matrix by binary searching the value, the way this lesson's part on the answer searched the rates.
How do you search a sorted list that was rotated?
[40, 50, 60, 10, 20, 30] was sorted, then cut and swapped. Find a value in O(log n).
[40, 50, 60, 10, 20, 30] was sorted, then cut and swapped. At which index does the moved part start?
How do you find a real number to a tolerance?
The same loop finds a real number. Say you want , the square root of x: it's the point where , the middle squared, reaches x. With floats, mid = (lo + hi) / 2, and the moves become lo = mid or hi = mid.
The trap is the stopping rule. while hi - lo > 1e-12 found in 41 steps. For it never stopped. After 10,000 steps, lo was 999999.9999999999 and hi was 1000000.0:
import math
lo, hi = 999999.9999999999, 1000000.0
print(math.nextafter(lo, hi) == hi)
print((lo + hi) / 2)
print(math.ulp(1e6))
True
1000000.0
1.1641532182693481e-10
math.nextafter(lo, hi) is the next float after lo, toward hi, and it is hi. So the two are neighbors, with no float between them, and the middle rounds to one of them. math.ulp(1e6) gives the gap between floats near a million: about 1.16e-10. No tolerance of 1e-12 can get under that gap.
Loop a fixed number of times instead. Each round halves the interval:
def square_root(x, rounds=100):
lo, hi = 0.0, max(1.0, x)
for _ in range(rounds):
mid = (lo + hi) / 2
if mid * mid < x:
lo = mid
else:
hi = mid
return hi
print(square_root(2), math.sqrt(2))
print(square_root(1e12), math.sqrt(1e12))
1.4142135623730951 1.4142135623730951
1000000.0 1000000.0
Return hi, the bound whose square is at least x. lo ends one float below it. Or stop on a tolerance relative to the size of the answer.
In the editor, write cube_root(x) with a fixed number of rounds, for any real x. Unlike a square root, a cube root exists for a negative number, so -8 must give -2. It prints the cube roots of 27, 1e18, 0.001 and -8.
How do you keep a list sorted while it changes?
insort is O(n) per insert: the insort step measured 229.81 µs for an insort and a removal on a million items. That's fine for a few inserts, and wrong for a stream of them:
- When you only need the smallest, use a heap. It hands back its smallest item and takes a new one in O(log n), and the next lesson builds one.
- When you need order, ranks and deletes from the middle, use a balanced search tree, O(log n) for each. Python's standard library doesn't have one. The third-party
sortedcontainerspackage provides aSortedListfor that job. - When all the items arrive before the first question, append them and sort once: 12.9 ms against 484.0 ms for 100,000.
For the practice problem, how do you keep only the last 30 days?
Old history can go, as long as the reads that still need it can find it.
Times 100, 130, 160, 220 and 300, and a cutoff of 200. Which changes must you keep?
What if the history is too big for one machine?
Shard by key: hash each key to one machine. A key's whole history then lives in one place, and a read is one machine and one binary search.
Old history can move to files sorted by key and time, with a small index of the first entry in each block. Binary search the index, then the block.
What about many writers at once?
The two lists must change together.
times is [100, 160, 220] with values [30, 45, 60]. A writer inserts time 130 with value 40, but a reader of time 140 runs between the two inserts. What does it read?
How do you read the whole store as of a time?
Call get once per key, so it's O(k log c) for k keys with up to c changes each. If the same moment is asked for again and again, build that view once and keep it. Throw it away when a late change lands before that moment.
What tests would you write?
First, a twin that scans every change. Run it side by side with the real store on thousands of random operations full of ties and late writes, and compare every read.
Then the edges, by hand:
- a read before the first change, exactly at a change, and after the last one
- a tie
- a key that was never set
- a delete followed by a set
- a key first set after a snapshot
The practice problem, start to finish
That's every piece the practice problem needs. It asks for the three levels from the start of the lesson, from a blank file, and the interviewer follows up after each one.
1.
times = [100, 130, 130, 130, 220]. What dobisect_left(times, 130)andbisect_right(times, 130)return?2.A binary search uses
lo, hi = 0, len(a)andwhile lo < hi, withmid = (lo + hi) // 2. Someone writeslo = midin the branch wherea[mid]is below the target. What happens?3.A store keeps each key's change times sorted in
timesand the values invalues. A read doesvalues[bisect_right(times, t) - 1]. What does it return for atbefore the key's first change?4.A log of
(key, time, value)arrives out of order, and two changes can share a time, in which case the later one wins. Values can be dicts. How should you sort it before building each key's history?5.Which of these questions can you answer with a binary search on the answer?
6.A store with 10,000 keys takes a snapshot after every 100 changes. One design copies every key's current value at each snapshot. The other keeps, per key, a list of (snapshots taken so far, value) after each change, and a snapshot only adds 1 to a counter. What does a snapshot cost in each?
Practice
Sources (12)
- Sorting Techniques: Key Functions · Python 3.12 documentation · Oct 26, 2026
“This technique is fast because the key function is called exactly once for each input record.”
- Sorting Techniques: Sort Stability and Complex Sorts · Python 3.12 documentation · Oct 26, 2026
“Sorts are guaranteed to be stable. That means that when multiple records have the same key, their original order is preserved.”
- Sorting Techniques: Odds and Ends · Python 3.12 documentation · Oct 26, 2026
“The reverse parameter still maintains sort stability (so that records with equal keys retain the original order).”
- Built-in Types: list.sort · Python 3.12 documentation · Oct 26, 2026
“To remind users that it operates by side effect, it does not return the sorted sequence”
- Objects/listsort.txt at v3.12.16 · CPython source code · Oct 25, 2026
“It has supernatural performance on many kinds of partially ordered arrays (less than lg(N!) comparisons needed, and as few as N-1)”
- Extra, Extra - Read All About It: Nearly All Binary Searches and Mergesorts are Broken · Google Research blog · Jun 2, 2006
“Specifically, it fails if the sum of low and high is greater than the maximum positive int value”
- bisect: bisect_left · Python 3.12 documentation · Oct 26, 2026
“The returned insertion point ip partitions the array a into two slices such that all(elem < x for elem in a[lo : ip]) is true for the left slice and all(elem >= x for elem in a[ip : hi]) is true for the right slice.”
- bisect: bisect_right · Python 3.12 documentation · Oct 26, 2026
“Similar to bisect_left(), but returns an insertion point which comes after (to the right of) any existing entries of x in a.”
- bisect: the key parameter · Python 3.12 documentation · Oct 26, 2026
“To support searching complex records, the key function is not applied to the x value.”
- bisect: insort_left · Python 3.12 documentation · Oct 26, 2026
“Keep in mind that the O(log n) search is dominated by the slow O(n) insertion step.”
- heapq: merge · Python 3.12 documentation · Oct 26, 2026
“does not pull the data into memory all at once”
- math: ulp · Python 3.12 documentation · Oct 26, 2026
“Return the value of the least significant bit of the float x”