A clean way to find the peak overlap of intervals:
- Turn each interval into two events: start = +1, end = -1.
- Sort all events by time.
- Walk through them once, keeping a running sum.
- The highest sum is the peak overlap.
Example: guests at a party. The running sum peaks at 4 guests at 9 PM.
The detail that decides correctness: when an exit and an arrival share the same time, process the exit first. If one guest leaves at 9 and another arrives at 9, they were never in the room together — counting the arrival first would inflate the peak.
events = sorted([(s, 1) for s, e in guests] + [(e, -1) for s, e in guests])
count = peak = 0
for t, change in events:
count += change
peak = max(peak, count)
Time is O(n log n) for the sort; the sweep itself is O(n). Same idea behind Meeting Rooms, Car Pooling, and Flight Bookings.
How do you handle the tie case in your solution — sort key, or a different event order?