Predict the output
What does this print?
blocks: list[list[int]] = []
for s, e in sorted([[1, 10], [2, 3], [4, 12]]):
if blocks and s <= blocks[-1][1]:
blocks[-1][1] = e
else:
blocks.append([s, e])
print(blocks)Choose an answer, then open Show answer below to check it.
Show answer
Answer: A [[1, 3], [4, 12]]
Right: [2, 3] overwrote the block's end with 3, so [4, 12] no longer looked like an overlap.
Using max() for the new end stops a short booking from cutting a longer block, and then the answer becomes one block.
Why not the others?
- B [[1, 12]]. That is what a correct merge returns; this version lost the end of [1, 10] at the second booking.
- C [[1, 10], [4, 12]]. After [2, 3] the block's end is 3, not 10.
Steps come from running the Python solution.
Text version
Five bookings:
Intervals in input order: [1, 3], [8, 10], [2, 6], [9, 12], [15, 18].
- Take [1, 3]; merged [1, 3]. [1, 3] starts a new block
- Take [2, 6]; merged [1, 6]. [2, 6] overlaps: extend to 6
- Take [8, 10]; merged [1, 6], [8, 10]. [8, 10] starts a new block
- Take [9, 12]; merged [1, 6], [8, 12]. [9, 12] overlaps: extend to 12
- Take [15, 18]; merged [1, 6], [8, 12], [15, 18]. [15, 18] starts a new block
Result: [[1, 6], [8, 12], [15, 18]]
Four bookings that touch:
Intervals in input order: [5, 7], [1, 2], [2, 4], [7, 9].
- Take [1, 2]; merged [1, 2]. [1, 2] starts a new block
- Take [2, 4]; merged [1, 4]. [2, 4] overlaps: extend to 4
- Take [5, 7]; merged [1, 4], [5, 7]. [5, 7] starts a new block
- Take [7, 9]; merged [1, 4], [5, 9]. [7, 9] overlaps: extend to 9
Result: [[1, 4], [5, 9]]