#5 · Off by one

Find the bug · #5 · Off by one Hard Python

Back-to-back meetings don’t merge

A calendar merges overlapping meetings into busy blocks, but meetings that touch stay apart.

On this page

The report

Bug report

A calendar works out each person’s busy time by merging overlapping meetings into blocks. Someone with meetings at 9–10 and 10–11 sees two separate blocks instead of one busy morning, and the “find a free slot” feature gets confused.

The code

Read it first: what should it do? Then click the line where you think the bug is.

PythonClick the line you think is wrong
def merge_meetings(meetings):
    """Merge overlapping meetings into blocks of busy time. A meeting is (start, end)."""
    merged = []
    for start, end in sorted(meetings):
        if merged and start < merged[-1][1]:
            merged[-1][1] = max(merged[-1][1], end)
        else:
            merged.append([start, end])
    return [tuple(m) for m in merged]

Read it, then pick a line.

What it prints

Running it on a small example prints the output on the left. It should print the output on the right.

The example
print(merge_meetings([(9, 10), (10, 11), (13, 14)]))

It prints

[(9, 10), (10, 11), (13, 14)]

It should print

[(9, 11), (13, 14)]
Show the answer: the bug, the fix, and how you’d find it

The bug (line 5)

Line 5 merges only when the next meeting starts strictly before the current block ends (<). Back-to-back meetings start exactly when the last one ends, so they stay separate. Busy time that touches should merge: it needs <=.

The fix

2    """Merge overlapping meetings into blocks of busy time. A meeting is (start, end)."""3    merged = []4    for start, end in sorted(meetings):5        if merged and start < merged[-1][1]:5        if merged and start <= merged[-1][1]:6            merged[-1][1] = max(merged[-1][1], end)7        else:8            merged.append([start, end])

How you’d find it

  1. Reproduce with the reported pair: (9, 10) and (10, 11). You expect one block, (9, 11); you get two.
  2. Try meetings that really overlap, (9, 12) and (10, 11): they merge fine. So the logic works, and the bug is at one exact edge: a start equal to the previous end.
  3. Read the comparison with that edge in mind: 10 < 10 is false, so they don’t merge.

The test that catches it

It fails on the code above and passes once it’s fixed. Keep it, so the bug can’t come back.

assert merge_meetings([(9, 10), (10, 11)]) == [(9, 11)]
assert merge_meetings([(9, 12), (10, 11)]) == [(9, 12)]
assert merge_meetings([(14, 15), (9, 10)]) == [(9, 10), (14, 15)]
assert merge_meetings([]) == []

Where else this bites

  • LeetCode’s Merge Intervals: whether [1, 3] and [3, 5] merge is exactly this.
  • Room booking: is a room that’s free from 10:00 free at 10:00?
Your progress stays on this device.