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
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.
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.
One meeting ends at 10 and the next starts at 10. Does the code think they overlap?
What it prints
Running it on a small example prints the output on the left. It should print the output on the right.
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
- Reproduce with the reported pair: (9, 10) and (10, 11). You expect one block, (9, 11); you get two.
- 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.
- Read the comparison with that edge in mind:
10 < 10is 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?