Three problems about covering a line with intervals. The move: keep an edge, look only at the intervals that touch it, and take the pick that pushes the edge farthest.
You work on a search service, a payments back end and a video app. The three problems on this street put intervals on a line, and each asks for the fewest picks that leave no gap.
What a pick is, and what it must reach, changes from problem to problem. Here is each rule.
| Problem | What must be reached | A pick is | Sort by |
|---|---|---|---|
| Cover the traffic spikes with the fewest cache windows | every spike minute | a window from a list | start |
| Fewest batch runs at the allowed times | every transaction window | a run at an allowed minute | close |
| Stitch clips that overlap enough | the whole length of a reel | a clip from a list | start |
All three keep one number: the edge. Everything before the edge is settled. The edge only moves forward, and each step makes the one pick that moves it farthest.
The answer is -1 whenever the best pick cannot move the edge at all. You will meet that case in every problem, so check for it before you count a pick.
Exercise · Predict the output: How many windows cover the spikes?. The spikes and the windows are sorted by start. At each uncovered spike the code takes the farthest end among the windows that start in time. What does it print?
spikes = [2, 3, 7, 8, 12]
windows = [[0, 4], [1, 3], [5, 7], [6, 9], [10, 12], [11, 13]]
j = 0
i = 0
best = -1
count = 0
while i < len(spikes):
s = spikes[i]
while j < len(windows) and windows[j][0] <= s:
best = max(best, windows[j][1])
j += 1
count += 1
while i < len(spikes) and spikes[i] <= best:
i += 1
print(count)Before you code, answer two questions. What is settled, and which picks touch the edge of what is settled?
For a cover, the edge is the first spike that no pick reaches yet. A window touches it when it starts at or before that spike, and the best of them is the one with the farthest end. After that pick, every spike up to its end is settled, so the edge jumps past them.
For settling windows with allowed points, turn the problem around. The window that closes first needs a run no later than its close. Of the allowed minutes up to that close, the latest one also settles the most windows that open later.
Everything before the edge is settled with as few picks as possible. Of the picks that touch the edge, take the one that moves the edge farthest. No other pick leaves the next step with more choices.
After the sort, both pointers move forward and never back, so the scan reads each interval once. The sort is the only super-linear part.
Take the farthest end among the windows that start in time, then skip every spike it covers.
Exercise · Find the bug: The window that starts at the spike. This covers the spikes with the fewest windows from a list, or returns -1 when a spike has no window. It is wrong on some inputs. Which line is wrong?
def fewest_windows(spikes, windows):
pts = sorted(spikes)
wins = sorted(windows)
j = 0
i = 0
count = 0
best = -1
while i < len(pts):
s = pts[i]
while j < len(wins) and wins[j][0] < s:
best = max(best, wins[j][1])
j += 1
if best < s:
return -1
count += 1
while i < len(pts) and pts[i] <= best:
i += 1
return countThe Academy lesson Greedy choices picks the most talks that do not overlap, by earliest end. Sort, then choose shows how to find the sort key with an exchange argument. This street does not teach those again. It changes three things.
The goal flips from packing to covering. Packing wants intervals that do not touch, so earliest end first is right. Covering wants no gap, so the key is the start, and the pick is the farthest end.
Take the spikes 1, 4, 6, 9, 10 and the windows [0,3] [2,5] [4,7] [5,6] [8,12] [9,10]. The farthest-end rule needs 3 windows. Earliest end first needs 4, and so does the first window that covers the spike.
The points may be a list too. In the batch run problem the minutes are not free. Sort the windows by close, and keep a pointer into the sorted run minutes.
For [1,5] [2,8] [7,12] [10,14] [13,16] with the runs 3, 6, 9, 12, 15, three runs settle everything. With the runs 3, 6, 9, 15 the answer is -1, because no run falls inside [10,14].
A join may need an overlap. In the stitching problem the next clip must start at least overlap seconds before the reel ends. Only the test for which clips start in time changes: it compares the start with the edge minus the overlap.
Take one list of six clips and a reel of 20 seconds. An overlap of 0 needs 3 clips, an overlap of 2 needs 4, and an overlap of 3 gives -1.
Earliest end first packs intervals but leaves a cover short: here it needs four windows where the farthest end needs three.
Exercise · Break it: Sorted by the wrong end. This counts the fewest batch runs that settle every window, with runs only at the allowed minutes. It sorts the windows by opening minute. Find an input where it gives the wrong count.
def fewest_runs(windows, runs):
times = sorted(runs)
order = sorted(windows, key=lambda w: (w[0], w[1]))
last = None
count = 0
p = 0
for start, close in order:
if last is not None and start <= last:
continue
while p < len(times) and times[p] <= close:
p += 1
if p == 0 or times[p - 1] < start:
return -1
last = times[p - 1]
count += 1
return countSolve them in this order. The first covers points with a list of windows. The second turns the roles around and allows only some minutes. The third adds the overlap.
Before you code each problem, write two lines: what the edge is, and which picks touch it. Then name the sort key. If the picks you may choose from do not touch the edge, the problem is not a cover.
Give each problem about 25 minutes. Spend the first five on the two lines and on a hand trace of a small case, then code it.
Three edge cases come back on every rung. Nothing reaches the edge, which means -1. Two picks tie on the farthest end. The first interval does not start where the line starts.
Write one small test for each. When a solution fails, check the strictness of each comparison first. Both ends of an interval count, so most wrong answers on this street are a strict test where a loose one belongs.
Checkpoint · Interval greedy
Q1/5 You cover spikes with windows from a list. At the first uncovered spike, which window do you take?
Answer: B
Every window that starts in time touches the edge. The farthest end moves the edge the most, so no other choice leaves the next step with more options.
Q2/5 On the spikes 1, 4, 6, 9, 10 with six windows, the farthest-end rule needs 3 windows. How many does earliest end first need?
Answer: C
Earliest end first is the right rule for packing intervals that do not touch, not for covering a line. It leaves the edge short, so an extra window is needed.
Q3/5 Transactions have windows, and runs may happen only at allowed minutes. How do you sort the windows?
Answer: C
The window that closes first needs a run no later than its close. Sorted by open, a run chosen late can be credited to a window that has already closed.
Q4/5 A reel needs each clip to start at least 2 seconds before the reel ends. Which part of the cover scan changes?
Answer: C
The farthest-end choice and the sort by start stay. Only the test for which clips touch the edge moves by the overlap.
Q5/5 When does a cover scan return -1?
Answer: B
If even the farthest end does not reach the first uncovered spike, no pick can move the edge, so the line cannot be covered.
Review cards from this lesson.
A few questions, then explain the idea back in your own words. Your tutor marks it. Quiz and explain back.