16/42
Part 4 of 8 · The sweepLearn and do

On closed days, a start goes first, or each end moves to the day after

Starts first isn't always wrong. It means that two intervals that share an instant both hold it, and that's what closed ends mean. On-call shifts (3, 5) and (5, 7), in closed days, both hold day 5. There, ends first is the bug. Either put starts first, or put each -1 at end + 1, so the shift (3, 5) is over at day 6:

# closed days: both hold day 5
shifts = [(3, 5), (5, 7)]
same_day = [(s, 1) for s, e in shifts] + [(e, -1) for s, e in shifts]
day_after = [(s, 1) for s, e in shifts] + [(e + 1, -1) for s, e in shifts]
# ends first
print(peak(same_day))
# starts first
print(peak(same_day, key=lambda e: (e[0], -e[1])))
# each end moved to end + 1
print(peak(day_after))
1
2
2

On 3,000 random sets of closed shifts, starts first and end + 1 both matched a count of every day. So the tie rule says what your ends mean:

  • Ends first: touching intervals don't overlap. That's half-open.
  • Starts first: touching intervals overlap. That's closed.

In the editor, most_on_one_day(shifts) runs the sweep on closed shifts. In its first loop, write the two events for each shift, with the end moved to the day after the shift's last day.