Lesson 4 of 4
Intervals
An interval is a pair [start, end]. In sorted order, the intervals that can overlap sit next to each other, so one walk with a small notebook merges them, inserts a new one, removes the fewest so none clash, or counts how many run at once.
Test whether two intervals overlap, and ask whether touching counts
Merge overlapping intervals by sorting by start and comparing each one with the last merged interval
Insert an interval into a sorted, merged list in one walk with three phases
Remove the fewest intervals so none clash by keeping the one that ends first, and say why that is safe
Count the rooms a set of meetings needs with a sweep line over sorted starts and ends
Your events table has one row per app session: the minute it started and the minute it ended. One user had her phone and her laptop open at the same time, so her sessions overlap: [[6, 8], [1, 3], [2, 4]]. The product team asks a plain question: during which stretches was she active? The answer is [[1, 4], [6, 8]]. The sessions [1, 3] and [2, 4] run together; [6, 8] stands alone.
Pairs like these are called intervals, and interview problems about them come in four shapes: merge the ones that overlap, insert one more, remove the fewest so none overlap, and count how many run at once. All four start from sorted order, the sort-first-then-walk pattern from the first lesson of this module: three of them start by sorting, and insert is handed a list that is already sorted. Sorted, the intervals that can overlap sit next to each other, and one walk with a small notebook answers the question.
When do two intervals overlap?
An interval is a pair [start, end] with start <= end: a stretch of time, or of numbers, from start to end. In Python it is a list of two numbers, such as [1, 4]. A list of intervals is a list of those pairs, so if it is called intervals, then intervals[0][1] is the end of the first one.
Two intervals overlap when each one starts at or before the other one ends. For intervals a and b that is a[0] <= b[1] and b[0] <= a[1]. Why does that test work? Turn it around. Two intervals miss each other in only two ways: a ends before b starts (a[1] < b[0]), or b ends before a starts (b[1] < a[0]). The test says neither happens. These four cases cover what you will meet:
| a | b | what happens | overlap? |
|---|---|---|---|
| [1, 4] | [2, 5] | they share 2 through 4 | yes |
| [1, 3] | [3, 5] | they touch at 3 | depends on the rule |
| [1, 2] | [4, 6] | a gap from 2 to 4 | no |
| [2, 9] | [4, 5] | b sits inside a | yes |
Touching is the case that changes from problem to problem. If an interval stands for every number from start to end, then [1, 3] and [3, 5] share the number 3, so they overlap, and the test uses <=. If an interval is a meeting, [1, 3] is over at 3, so another meeting can start at 3 in the same room, and the test becomes strict: a[0] < b[1] and b[0] < a[1]. The rooms figure later in this lesson writes a meeting as [1, 5), a half-open interval: the ) means it runs from 1 up to 5, and 5 itself is not included. In an interview, ask which rule applies before you write the comparison.
Type exactly what this prints, one value per line. The test counts touching as overlapping.
def overlaps(a, b):
return a[0] <= b[1] and b[0] <= a[1]
print(overlaps([1, 4], [2, 5]))
print(overlaps([3, 5], [1, 3]))
print(overlaps([6, 8], [1, 5]))
print(overlaps([2, 9], [4, 5]))
Sort by start, then merge in one walk
How do we merge every group of overlapping intervals? The direct way checks every pair, merges a pair that overlaps, and starts the search over, because the merged interval may now reach a third one. Five intervals make 10 pairs, and n intervals make n(n − 1)/2. One search is already O(n2), and each merge starts another one, where O(n2) means the work grows like n times n.
Sorting by start puts partners next to each other. Walk the intervals in start order and keep a list of merged intervals. Two facts hold at every step. Every earlier merged interval ended before the last merged one started (otherwise they would have merged). And the next interval starts at or after the last merged interval's start. Put together: every earlier merged interval ends before the next interval starts. So the next interval can only overlap the last merged interval, and that is the only comparison we need.
The figure draws five intervals on a timeline, one lane each in start order, with the merged intervals in their own lane at the bottom. The chips above it list the intervals in the order they arrived. The blue line marks the start of the interval being checked; the dashed teal line marks the end of the last merged one. Before you press Next, guess how many merged intervals come out.
One comparison decides each step: does the next interval start at or before the last merged end? If yes, they overlap, and the last merged end becomes the larger of the two ends. If no, there is a gap, and the interval starts a new merged interval. The larger end matters: [2, 3] sat inside [1, 4], and copying its end would have shrunk [1, 4] to [1, 3].
Here is the same walk in Python, on the same five intervals. key=lambda pair: pair[0] tells sorted what to compare. A lambda, from the sorting lesson, is a one-line function with no name; this one takes a pair and returns its start. for start, end in ordered unpacks each pair into two names. merged[-1] is the last merged interval, so merged[-1][1] is its end.
if merged and ... guards that read. An empty list counts as false, and and skips its right side when the left is false, so merged[-1] is never read while merged is empty. Before you step through, guess how many times line 6, the max line, runs.
def merge_intervals(intervals):ordered = sorted(intervals, key=lambda pair: pair[0])merged = []for start, end in ordered:if merged and start <= merged[-1][1]:merged[-1][1] = max(merged[-1][1], end)else:merged.append([start, end])return merged
(nothing printed yet)Recap. Sort by start, then compare each interval with the last merged one only. An overlap grows the end with max; a gap starts a new merged interval. Now put the lines in order yourself.
Put the lines in order to build merge_intervals(intervals), which merges every group of overlapping intervals (touching counts as overlapping). Indentation is already part of each line. Two of the lines do not belong.
Add lines from the list below, in order.
for start, end in sorted(intervals, key=lambda pair: pair[0]):else:merged.append([start, end])if merged and start <= merged[-1][1]:if merged and start < merged[-1][1]:merged[-1][1] = endmerged[-1][1] = max(merged[-1][1], end)return mergedmerged = []def merge_intervals(intervals):
The full problem asks for this function from a blank editor. Its tests include touching intervals, an interval inside another, and 20,000 intervals out of order, where checking every pair is too slow.
The sort is the main cost: O(n log n), then one O(n) walk. Two details decide the tests: <=, because touching intervals merge in this problem, and max, because an interval can sit inside the last one.
The product team's next question: how many minutes was she active in total? Her three sessions, [6, 8], [1, 3] and [2, 4], last 2 minutes each, 6 in all. But the minute from 2 to 3 is in two of them, so she was active for only 5: from 1 to 4, then from 6 to 8. Adding up every session's length counts the overlaps twice. Merge first, then add.
Each item of sessions is [start, end]: a session from minute start to minute end, which lasts end - start minutes. Sessions can overlap and come in any order. Write busy_time(sessions), which returns the number of minutes covered by at least one session. A minute covered by two sessions counts once.
raise NotImplementedError, then press Run tests. Each check says what it expects.Inserting into a merged list
What if the list is already sorted and merged, and one new interval arrives? You could append it and merge again, but that sort costs O(n log n), and the input already gives you the order.
The intervals the new one overlaps form one unbroken stretch. The list is sorted by start and nothing in it overlaps, so each interval ends before the next one starts: the ends are in order too. So the list splits into three parts, in order: intervals that end before the new one starts, intervals that overlap it, and intervals that start after it ends. Call the new interval's ends start and end. One walk with one index, i, then works in three phases:
- Before: while
intervals[i][1] < start, copy the interval to the result. - Overlap: while
intervals[i][0] <= end, absorb it:startbecomes the smaller of the two starts andendthe larger of the two ends. - After: append
[start, end], then copy the rest.
The trace inserts [4, 8] into [[1, 2], [3, 5], [6, 7], [9, 10]], with touching counted as overlapping. The arrow i moves along the list. Before you step through, guess the result.
def insert_interval(intervals, new_interval):start, end = new_intervalresult = []i = 0while i < len(intervals) and intervals[i][1] < start:result.append(intervals[i])i += 1while i < len(intervals) and intervals[i][0] <= end:start = min(start, intervals[i][0])end = max(end, intervals[i][1])i += 1result.append([start, end])while i < len(intervals):result.append(intervals[i])i += 1return result
(nothing printed yet)Why < in phase 1 and <= in phase 2? Because touching counts as overlapping here. An interval that ends exactly at start shares that number, so phase 1 must not copy it. An interval that starts exactly at end shares that number, so phase 2 absorbs it.
Many rounds have no run button, so practice the phases by hand on a new input.
On paper, run the three phases of insert_interval on intervals = [[1, 3], [5, 6], [8, 9], [11, 12]] and new_interval = [4, 8]. For each value of i, write the phase, the test and start, end afterwards. Then reveal the steps one at a time.
Work it on real paper: writing each step is the point. Then check your final answer here and compare your working with the walk-through.
Type a number: 12, -1, 0.5 and 3/4 all work. Enter checks.
Now write it. The tests add an empty list, a new interval before or after everything, and one that touches both of its neighbors.
One walk, no sort: O(n). Appending and merging again is a fine first answer to say out loud; the three phases improve on it by using the order the input promises.
Remove the fewest: keep the one that ends first
The next problem uses the meeting rule. Each interval is a booking of one room from start until end, and two bookings clash when each one starts before the other ends. A booking that ends at 4 and one that starts at 4 do not clash. The question: what is the smallest number of bookings to remove so that no two of the rest clash?
Removing the fewest is the same as keeping the most. So build the kept set one booking at a time. The plan is greedy, like the shipping check in the previous lesson: at each step, make the choice that looks best right now and never take it back. A greedy plan is only as good as its choice, so pick one before you see the code.
You want to keep the most bookings with no clashes (a booking may start exactly when another ends). The plan: pick one booking to keep, drop everything that clashes with it, and repeat on what is left. Which first pick is always safe?
Choose one answer, then check.
Why is ending first safe? Swap it into any best answer, and nothing is lost. Take any best set of kept bookings and look at its booking that ends first. Every other booking in the set starts at or after that end, because none of them clashes with it and none ends sooner. Now swap in the booking that ends first overall. It ends no later, so the rest of the set still fits after it, and the set keeps its size. So some best answer keeps the earliest-ending booking, and the same argument repeats on the bookings that start at or after its end. This is an exchange argument: swap your choice into any best answer and show that nothing is lost.
In code: sort by end, and remember last_end, the end of the last kept booking. A booking that starts at or after last_end fits, so keep it. Any other booking starts before last_end and ends at or after it, so it clashes with the last kept booking: remove it. last_end starts at float("-inf"), a value smaller than every number, so the first booking is always kept. Before you step through, guess how many of these four bookings are removed.
def min_removals(intervals):ordered = sorted(intervals, key=lambda pair: pair[1])removed = 0last_end = float("-inf")for start, end in ordered:if start >= last_end:last_end = endelse:removed += 1return removed
(nothing printed yet)The problem adds equal bookings, negative times, and a test that catches keeping the shortest booking first.
>=, not >, because touching bookings do not clash. With >, the problem's first example, [[1, 3], [2, 4], [3, 5]], would also remove [3, 5] and answer 2 instead of 1.
Counting rooms with a sweep line
How many rooms do the meetings need? Exactly the most meetings running at the same moment. At least that many, because each running meeting needs its own room. And that many is enough: when a meeting starts, the meetings running then, itself included, are no more than that peak, so a free room is waiting. Meetings use the [start, end) rule again: a room is free the moment its meeting ends.
The count of running meetings only goes up when a meeting starts, so the busiest moment is always right after some start. The brute force checks each meeting's start time and counts the meetings running then: n counts over n meetings, O(n2).
A sweep line counts in one pass. Picture a vertical line moving left to right through time. Every start it crosses takes a room, and every end gives one back. Write each start and each end as an event, sort the events by time, and keep a running count of rooms in use. When an end and a start happen at the same time, the end goes first, because a meeting that ends at 4 frees its room for one that starts at 4.
The figure sweeps through four meetings, one lane each. The chips under the timeline are the events in sweep order. Before you press Next, guess the most rooms in use at once.
The code sweeps through the starts only, since the busiest moment always comes right after some start. Sort the start times and the end times as two separate lists; lines 2 and 3 build each one with a list comprehension. We never need to know which end belongs to which meeting, only how many meetings have ended by now. Before counting each start, release every meeting whose end is at or before it. The arrow j marks the earliest end not yet released. Before you step through, guess where j points when the call returns.
def min_meeting_rooms(meetings):starts = sorted([start for start, end in meetings])ends = sorted([end for start, end in meetings])in_use = 0most = 0j = 0for start in starts:while ends[j] <= start:in_use -= 1j += 1in_use += 1most = max(most, in_use)return most
(nothing printed yet)The while loop sits inside the for loop, but the sweep is not O(n2). Each pass of the inner loop moves j forward by one, and j never moves back. Across the whole sweep the inner loop runs at most n times, so the sweep is O(n), and the two sorts dominate.
ends[j] never runs off the end of the list, even with no j < len(ends) check. A meeting that is over by now started before now, so its start was already counted. So j, the number of meetings released, never passes the number of starts counted so far, which is less than n. That needs start < end for every meeting, which the problem below promises.
The tie rule is where this code most often goes wrong. Sweep this one by hand.
What does min_meeting_rooms([[1, 5], [2, 3], [3, 6], [5, 7]]) return? Each meeting is [start, end): a room is free the moment its meeting ends. Sweep by hand with starts = [1, 2, 3, 5] and ends = [3, 5, 6, 7].
Type a number: 12, -1, 0.5 and 3/4 all work. Enter checks.
The problem adds an empty list, identical meetings, and 18,000 meetings for the speed check.
You will also see a heap of end times. A min-heap (module 9) is a structure that hands back its smallest item quickly. Sort the meetings by start and keep one end time per room in the heap. For each meeting, if the earliest end in the heap is at or before its start, that room is free: take that end out. Then put the meeting's own end in. The heap's size at the end is the number of rooms. It is also O(n log n); the two-list sweep needs nothing beyond sorting.
Last, say the rooms plan out loud, the way you would before typing.
An interviewer asks for the fewest meeting rooms that fit a list of meetings. Say what you would say before typing: the brute force and its cost, then the sweep with its walk, notebook, promise and cost, and the rule for a meeting that ends exactly when another starts.
Saved in this browser as you type.