Six problems that choose or count intervals instead of merging them. The move: sort by the end that closes decisions first, and keep only the open intervals where the best one is at hand.
You work on the back end of a social app, a payments app, a monitoring system, an exam portal, an ad platform and a delivery app. Six problems on this street come from them. Each one has intervals, and none of them asks for the merged ranges.
They ask you to choose some intervals, or to count how many are open. Each asks for something different, and each has its own sort key.
| Problem | What you choose or count | Sort by |
|---|---|---|
| Fewest announcements to reach every show | the fewest points that touch every interval | end |
| Most offers you can claim | the most intervals that get a day each | start, with the open ends in a heap |
| Alerts firing at each query time | how many intervals contain a time | starts and ends, each on its own |
| Courses before their deadlines | the most courses that finish on time | deadline |
| Tightest campaign for each day | the shortest interval that contains a day | start, with the questions sorted too |
| Job scheduling for the best profit | the best total of jobs that do not overlap | end |
The sorts differ because the questions differ. The rest of the lesson explains how to choose.
Here is the first row as code. Sort the shows by end, and place a notification at the end of the first show that no earlier notification reaches.
Exercise · Put it in order: The fewest notifications. Arrange the lines into a function that returns the fewest notification times that reach every show. A notification at second t reaches the shows with start <= t <= end.
def fewest_pings(shows):
shows.sort(key=lambda s: s[1])
count = 0
last = -1
for start, end in shows:
if start > last:
count += 1
last = end
return count
shows.sort()
if start >= last:The move has three steps, and you take them before you write code.
First, find the end that closes a decision: a deadline, an expiry or an end of a job. Second, sort so that these come in order. Third, name the structure that holds the intervals still open, and write what its top gives you.
Process the intervals in the order that closes decisions first, and keep only the open ones in a structure that gives the best candidate at once. Everything else can no longer matter, so each step is one look at the top.
The structure changes with the question, and the table lists the five you need.
Sort the shows by end, notify at the end of the first show not yet reached, and skip every show that starts at or before it.
| The question | The structure | The top gives you |
|---|---|---|
| The fewest points | the last point placed | whether the next interval is already reached |
| The most offers, one a day | a heap of the ends of open offers | the offer that expires first |
| How many contain a time | sorted starts and sorted ends | a count from two binary searches |
| The most courses by their deadlines | a list of the courses taken | the longest one, to give back |
| The best total profit | a table of the best total up to each end | the best total before a start |
The courses show the fourth row. Take the courses in order of their last day. After each one, add its days to the total. If the total passes the last day, give back the longest course taken so far.
This is not a hope that the greedy choice was right. Giving back the longest course keeps the number of courses and makes the total as small as it can be, so every later course has the most room.
Exercise · Predict the output: Giving back the longest course. The code takes courses in order of their last day. When the total passes the last day, it gives back the longest course taken. What does it print: the number of courses kept, then the total days?
courses = [[5, 5], [4, 6], [2, 6]]
courses.sort(key=lambda c: c[1])
taken = []
total = 0
for days, last in courses:
taken.append(days)
total += days
if total > last:
longest = max(taken)
taken.remove(longest)
total -= longest
print(len(taken), total)The Academy lesson Intervals sweeps events and merges ranges. Sort, then choose: exchange arguments and intervals proves when a sorted greedy rule is safe. Greedy with a heap and Scheduling with heaps keep the best choice in a heap.
This street does not teach those again. It changes three things about them.
The sort key follows the question. For points and for profit, you sort by end. For the offers and the campaigns, you sweep by start and let a heap hold the ends. Sorting by the wrong end gives a plausible answer that is wrong.
The questions are sorted too. The campaign problem gives a list of days to ask about. Sort the days, answer them in time order with one heap, and write each answer back to its original place. With 100,000 campaigns and 100,000 days, checking each pair costs 10,000,000,000 checks.
Counting uses two sorted lists. The alerts at a time are the starts at most t, minus the ends below t. Each question is two binary searches, and log base 2 of 100,000 is 16.6, so about 17 steps each. An end counts on its last second, and that is the edge case to test.
An alert is still firing on its last second, so count only the ends strictly below the question time.
Exercise · Find the bug: The alert that ends this second. This counts the alerts firing at each query time: the starts at most t, minus the alerts that have stopped. Both ends of an alert count as firing. Which line is wrong?
def firing_counts(alerts, queries):
starts = sorted(a[0] for a in alerts)
ends = sorted(a[1] for a in alerts)
def count_at_most(values, x):
lo, hi = 0, len(values)
while lo < hi:
mid = (lo + hi) // 2
if values[mid] <= x:
lo = mid + 1
else:
hi = mid
return lo
result = []
for t in queries:
result.append(count_at_most(starts, t) - count_at_most(ends, t))
return resultGreedy rules are tempting on the last rung. Taking the most profitable job first looks safe, and the next block shows the input where it is not.
Exercise · Break it: The most profitable job first. This code takes the jobs from the most profitable down, and keeps each job that does not overlap one already taken. A job may start the moment another ends. Find an input where the total is not the best.
def best_profit(start, end, profit):
order = sorted(range(len(start)), key=lambda i: -profit[i])
taken = []
total = 0
for i in order:
if all(end[i] <= start[j] or end[j] <= start[i] for j in taken):
taken.append(i)
total += profit[i]
return totalSolve them in this order. The first three are medium, and each uses a different structure. The last three are hard, and they add regret, sorted questions and a table over sorted ends.
Before you code each problem, write three lines: the sort key, the structure that holds the open intervals, and what its top gives you. If a greedy rule seems obvious, write a small input that could break it.
Give each problem about 25 minutes. Spend the first five on the three lines, and say them out loud as you would to an interviewer. Then list the edge cases before you run anything.
Four edge cases come back on most rungs. A boundary can count on both ends, intervals can be equal, a heap can empty before the day ends, and totals can pass 32 bits. Write one small test for each.
When a solution fails, check the sort key first. Most wrong answers on this street come from the wrong end, or from a greedy rule that nobody tried to break.
Checkpoint · Scheduling with intervals
Q1/5 You place the fewest notifications so that every show is reached while it is on air. Why do you sort the shows by end?
Answer: B
The earliest end is the deadline for that show. Placing the notification at that end reaches every later show that is already on air. Sorting by start can fail: the shows 1 to 10, 2 to 3 and 5 to 6 give 1 instead of 2.
Q2/5 The alerts are 1 to 3 and 2 to 5, and both seconds of an alert count. How many alerts fire at second 3?
Answer: B
The starts at most 3 are 2, and no end is below 3, so 2 - 0 = 2. Counting the ends at most 3 would remove the first alert on its last second and give 1.
Q3/5 A student takes courses in order of their last day, and the total passes a last day. What does giving back the longest course taken do?
Answer: B
Dropping the longest course and keeping the new one leaves the count unchanged. The total becomes the smallest possible, so every later course has the most room.
Q4/5 The jobs are 0 to 10 paying 60, 0 to 5 paying 40 and 5 to 10 paying 40. What is the best total, and what does the most-profitable-first rule give?
Answer: C
The two shorter jobs fit side by side and pay 80. The greedy rule takes the 60 first, and the other jobs then overlap it.
Q5/5 For the tightest campaign on each day, why are the days sorted too?
Answer: C
Sweeping time once with a heap of open campaigns answers each day when the sweep reaches it. The answers are then placed in the order the days came in.
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.