iq.lab
Python starts when a code cell comes near or you run one
06 Sorting and binary search

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.

About 2 hours 10 minutes, with the 4 problems worked in it
By the end you can
  • 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:

abwhat happensoverlap?
[1, 4][2, 5]they share 2 through 4yes
[1, 3][3, 5]they touch at 3depends on the rule
[1, 2][4, 6]a gap from 2 to 4no
[2, 9][4, 5]b sits inside ayes

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.

PredictOverlap or not

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.

Step throughMerging overlapping intervals
Step 1 of 32
Line 1 is about to run.
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
Names
no names yet
Output
(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 in orderPut the merge together

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.

Your program

Add lines from the list below, in order.

    Unused lines (some do not belong)
    • 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] = end
    • merged[-1][1] = max(merged[-1][1], end)
    • return merged
    • merged = []
    • 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.

    mediumSort by start and sweepSorting target 25 min

    Merge overlapping intervals

    Each item of intervals is a pair [start, end] with start ≤ end. It stands for every number from start to end, both ends included. Two intervals overlap when they share at least one number, so [1, 3] and [3, 5] overlap at 3, but [1, 2] and [3, 4] do not.

    Intervals that overlap, directly or through a chain of others, form a group. Replace each group with one interval that runs from the group's smallest start to its largest end. An interval that overlaps nothing is a group of one and stays as it is. Return the new intervals as a list of [start, end] lists, sorted by start. The input can come in any order.

    Example 1
    Inputintervals = [[1, 4], [2, 5], [7, 9]]Output[[1, 5], [7, 9]]

    [1, 4] and [2, 5] share 2 through 4, so they become [1, 5]. [7, 9] shares nothing.

    Example 2
    Inputintervals = [[6, 8], [1, 3], [2, 4]]Output[[1, 4], [6, 8]]

    The input is not sorted. [1, 3] and [2, 4] overlap; [6, 8] stands alone.

    Example 3
    Inputintervals = [[1, 3], [3, 5]]Output[[1, 5]]

    They share the number 3, so they count as overlapping.

    Constraints
    • 1 ≤ len(intervals) ≤ 105

    • 0 ≤ start ≤ end ≤ 105

    Plan it first

    Write a line for each before you code, then say them out loud. Compare with the Approach tab afterwards.

    ⌘+Enter runs 0:00Python starts when a code cell comes near or you run one
    Run examples checks the examples. Submit runs every test, including edge cases and, when the problem has one, a speed check on a large input.

    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.

    Code itTotal time active

    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.

    ⌘+Enter runsPython starts when a code cell comes near or you run one
    Write your code where the starter says 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:

    1. Before: while intervals[i][1] < start, copy the interval to the result.
    2. Overlap: while intervals[i][0] <= end, absorb it: start becomes the smaller of the two starts and end the larger of the two ends.
    3. 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.

    Step throughInserting an interval in three phases
    Step 1 of 25
    Line 1 is about to run.
    def insert_interval(intervals, new_interval):
    start, end = new_interval
    result = []
    i = 0
    while i < len(intervals) and intervals[i][1] < start:
    result.append(intervals[i])
    i += 1
    while i < len(intervals) and intervals[i][0] <= end:
    start = min(start, intervals[i][0])
    end = max(end, intervals[i][1])
    i += 1
    result.append([start, end])
    while i < len(intervals):
    result.append(intervals[i])
    i += 1
    return result
    Names
    no names yet
    Output
    (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 paperInsert by hand

    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.

    end of the merged interval

    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.

    mediumSort by start and sweep target 25 min

    Insert an interval

    intervals is a list of [start, end] pairs, both ends included, sorted by start. No two of them share a number. You get one more pair, new_interval.

    Put it into the list. Every interval that shares at least one number with it joins it, and together they become one interval from the smallest of their starts to the largest of their ends. Sharing only an endpoint counts, so [1, 2] and [2, 4] become [1, 4]. Return the resulting list of [start, end] lists, still sorted by start, with no two intervals sharing a number.

    Example 1
    Inputintervals = [[1, 2], [4, 6], [8, 10]], new_interval = [5, 8]Output[[1, 2], [4, 10]]

    [5, 8] shares 5 through 6 with [4, 6] and the number 8 with [8, 10], so all three become [4, 10].

    Example 2
    Inputintervals = [[1, 3], [7, 9]], new_interval = [4, 5]Output[[1, 3], [4, 5], [7, 9]]

    It shares nothing, so it goes in between, in start order.

    Example 3
    Inputintervals = [], new_interval = [2, 7]Output[[2, 7]]

    An empty list gets the new interval alone.

    Constraints
    • 0 ≤ len(intervals) ≤ 104

    • 0 ≤ start ≤ end ≤ 105

    • intervals is sorted by start, and no two of its intervals share a number.

    Plan it first

    Write a line for each before you code, then say them out loud. Compare with the Approach tab afterwards.

    ⌘+Enter runs 0:00Python starts when a code cell comes near or you run one
    Run examples checks the examples. Submit runs every test, including edge cases and, when the problem has one, a speed check on a large input.

    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.

    Quick checkWhich booking to keep first

    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.

    Step throughKeeping the booking that ends first
    Step 1 of 28
    Line 1 is about to run.
    def min_removals(intervals):
    ordered = sorted(intervals, key=lambda pair: pair[1])
    removed = 0
    last_end = float("-inf")
    for start, end in ordered:
    if start >= last_end:
    last_end = end
    else:
    removed += 1
    return removed
    Names
    no names yet
    Output
    (nothing printed yet)

    The problem adds equal bookings, negative times, and a test that catches keeping the shortest booking first.

    mediumSort by start and sweepGreedy choiceSorting target 25 min

    Fewest intervals to remove

    Each item of intervals is a pair [start, end] with start < end. Think of it as a booking of one room from start until end. 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 first is over when the second begins. The bookings come in any order.

    Remove as few bookings as you can so that no two of the bookings left clash, and return how many you removed.

    This endpoint rule is the opposite of merge intervals, where touching intervals merged. Check the rule in every interval problem.

    Example 1
    Inputintervals = [[1, 3], [2, 4], [3, 5]]Output1

    Remove [2, 4]. Then [1, 3] and [3, 5] only touch at 3, which is allowed.

    Example 2
    Inputintervals = [[1, 10], [2, 3], [4, 5], [6, 7]]Output1

    Remove the long [1, 10]. The three short bookings fit one after another.

    Example 3
    Inputintervals = [[3, 6], [3, 6], [3, 6]]Output2

    Equal bookings all clash with each other, so only one can stay.

    Constraints
    • 0 ≤ len(intervals) ≤ 105

    • -5 × 104 ≤ start < end ≤ 5 × 104

    Plan it first

    Write a line for each before you code, then say them out loud. Compare with the Approach tab afterwards.

    ⌘+Enter runs 0:00Python starts when a code cell comes near or you run one
    Run examples checks the examples. Submit runs every test, including edge cases and, when the problem has one, a speed check on a large input.

    >=, 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.

    Step throughCounting rooms with a sweep line
    Step 1 of 37
    Line 1 is about to run.
    def min_meeting_rooms(meetings):
    starts = sorted([start for start, end in meetings])
    ends = sorted([end for start, end in meetings])
    in_use = 0
    most = 0
    j = 0
    for start in starts:
    while ends[j] <= start:
    in_use -= 1
    j += 1
    in_use += 1
    most = max(most, in_use)
    return most
    Names
    no names yet
    Output
    (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.

    Work it outRooms when a meeting ends as one starts

    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].

    rooms

    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.

    mediumSort by start and sweepSortingTwo pointers target 25 min

    Meeting rooms needed

    Each item of meetings is a pair [start, end] with start < end: a meeting that needs a room from start until end. A room holds one meeting at a time, and it is free again the moment its meeting ends, so a meeting that ends at 3 and one that starts at 3 can use the same room. The meetings come in any order.

    Return the smallest number of rooms that lets every meeting happen.

    Example 1
    Inputmeetings = [[1, 4], [2, 5], [6, 8]]Output2

    [1, 4] and [2, 5] both run from 2 to 4. [6, 8] reuses a room.

    Example 2
    Inputmeetings = [[1, 3], [3, 5], [5, 7]]Output1

    Each meeting starts as the previous one ends, so one room is enough.

    Example 3
    Inputmeetings = [[0, 10], [1, 4], [2, 3], [5, 9]]Output3

    At time 2, [0, 10], [1, 4] and [2, 3] are all running.

    Constraints
    • 0 ≤ len(meetings) ≤ 105

    • 0 ≤ start < end ≤ 106

    Plan it first

    Write a line for each before you code, then say them out loud. Compare with the Approach tab afterwards.

    ⌘+Enter runs 0:00Python starts when a code cell comes near or you run one
    Run examples checks the examples. Submit runs every test, including edge cases and, when the problem has one, a speed check on a large input.

    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.

    Say itSay the rooms plan out loud

    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.

    A few sentences first: 0 of 60 characters.

    Saved in this browser as you type.

    Next: the module checkpoint