Predict the output
What does this print?
spans = [[1, 4], [2, 6], [8, 9]]
starts = [(s, 1) for s, _ in spans]
events = sorted(starts + [(e, -1) for _, e in spans])
live, last, covered = 0, 0, 0
for t, d in events:
if live:
covered += t - last
live += d
last = t
print(covered)Choose an answer, then open Show answer below to check it.
Show answer
Answer: A 6
Right: [1, 6) covers 5 and [8, 9) covers 1.
The running count decides whether time between events is covered, so overlaps are never double-counted.
Why not the others?
- B 8. Overlaps are counted once, not twice.
- C 4. The first two spans together cover 1 to 6.