Python 3D Academyবাংলা

Merging and inserting intervals

🌍 In real life. A doctor's calendar lists every appointment, and some overlap or run straight into each other. The receptionist wants to tell a patient when the doctor is busy, as a short list of busy stretches, not twenty separate bookings. Appointments from 1 to 3 and 2 to 6 are really one busy stretch, 1 to 6.

The idea in one sentence: sort the intervals by start; then each one either overlaps the block you are building, and stretches it, or starts after a gap, and begins a new block.

Its words:

  • interval: a stretch of time [start, end]
  • overlap: two intervals share some time; here touching, like [1, 4] and [4, 5], counts too
  • block: one merged interval in the answer

Step by step:

  1. sort the intervals by start
  2. take the first as the current block
  3. for each next interval: if it starts at or before the block's end, stretch the end to the larger of the two; otherwise the block is finished, and this interval starts a new one

Watch six busy stretches become three. Note that [9, 11] arrives after [15, 18] in the list, and sorting puts it where it belongs:

Why one pass after sorting is enough. Once sorted by start, every interval that could join the current block comes right after it: anything that starts after the block's end has a gap before it, and every later interval starts even later, so no later interval can reach back into a finished block. That is the greedy choice here: close a block as soon as a gap appears, and it is always safe.

Putting one new interval in. If the list is already sorted and merged, a new booking doesn't need a full sort. Walk once: copy the blocks that end before it starts, swallow every block that overlaps it into one, then copy the rest.

What it costs, by counting. Merging is the sort, O(n log n), plus one O(n) pass. For 100,000 appointments, about 1,700,000 comparisons, then 100,000 steps. Inserting into a merged list is O(n): one walk, no sort.

def merge(intervals):
    merged = []
    for s, e in sorted(intervals):                 # by start
        if merged and s <= merged[-1][1]:          # it overlaps (or touches) the last block
            merged[-1][1] = max(merged[-1][1], e)  # stretch the block, never shrink it
        else:
            merged.append([s, e])                  # a gap: start a new block
    return merged

def insert(intervals, new):
    s, e = new
    out, i, n = [], 0, len(intervals)
    while i < n and intervals[i][1] < s:           # wholly before the new one
        out.append(intervals[i])
        i += 1
    while i < n and intervals[i][0] <= e:          # overlaps it: swallow into one block
        s, e = min(s, intervals[i][0]), max(e, intervals[i][1])
        i += 1
    out.append([s, e])
    out.extend(intervals[i:])                      # wholly after it
    return out

print(merge([[1, 3], [2, 6], [8, 10], [15, 18], [9, 11], [17, 20]]))
print(insert([[1, 2], [3, 5], [6, 7], [8, 10], [12, 16]], [4, 8]))

Mistakes and edge cases.

  • forgetting to sort: the input is often unsorted; without sorting, [1, 3], [8, 10], [2, 6] gives [[1, 3], [8, 10]]: [2, 6] starts before 10, so it is swallowed into [8, 10], which it doesn't even touch
  • shrinking a block: [1, 10] then [2, 3] must stay [1, 10]; take max of the two ends, never just the new end
  • touching: whether [1, 4] and [4, 5] join depends on the problem; here they do (s <= end), for booked rooms often they don't
  • empty input: return an empty list
  • changing the input: merged[-1][1] = ... edits the list you built, not the caller's intervals, because each block is a new list

Quiz

  1. What does this print?

    def merge(intervals):
        merged = []
        for s, e in sorted(intervals):                 # by start
            if merged and s <= merged[-1][1]:          # it overlaps (or touches) the last block
                merged[-1][1] = max(merged[-1][1], e)  # stretch the block, never shrink it
            else:
                merged.append([s, e])                  # a gap: start a new block
        return merged
    
    print(merge([[1, 4], [4, 5], [7, 8]]))
  2. What does this print?

    def merge(intervals):
        merged = []
        for s, e in sorted(intervals):                 # by start
            if merged and s <= merged[-1][1]:          # it overlaps (or touches) the last block
                merged[-1][1] = max(merged[-1][1], e)  # stretch the block, never shrink it
            else:
                merged.append([s, e])                  # a gap: start a new block
        return merged
    
    print(merge([[1, 10], [2, 3], [4, 12]]))
  3. Why must the intervals be sorted by start first?

    • So every interval that can join a block comes right after it
    • So the longest interval comes first
    • Sorting isn't needed
  4. The list is already merged and sorted. How fast can one new interval be put in?

    • O(n): one walk, no sort
    • O(n log n): it must sort again
    • O(n²)
  5. merge([[1, 10], [2, 3]]) gives [[1, 3]]. Which line is wrong?

    def merge(intervals):
        merged = []
        for s, e in sorted(intervals):
            if merged and s <= merged[-1][1]:
                merged[-1][1] = e
            else:
                merged.append([s, e])
        return merged

Coding tasks

  1. Write merge(intervals): intervals is a list of [start, end] lists in any order. Return the merged blocks, sorted by start, as a list of [start, end] lists. Intervals that touch join too.

  2. Write insert(intervals, new): intervals is already sorted and merged (no two touch). Put the interval new in and return the list, still sorted and merged, without sorting again.