My Calendar III - Problem
You're building a smart scheduling system that tracks booking overlaps in real-time. Every time someone books a time slot [startTime, endTime), you need to determine the maximum number of events that overlap at any point in time.
A k-booking occurs when k events have some non-empty time intersection - meaning there's at least one moment when all k events are happening simultaneously.
Your task: Implement the MyCalendarThree class that can:
MyCalendarThree()- Initialize an empty calendarbook(startTime, endTime)- Add a new booking and return the maximum overlap count across all bookings
Note: Time intervals are half-open [start, end), so an event ending at time t doesn't conflict with an event starting at time t.
Input & Output
example_1.py โ Basic Booking Sequence
$
Input:
myCalendarThree = MyCalendarThree()
myCalendarThree.book(10, 20) # returns 1
myCalendarThree.book(50, 60) # returns 1
myCalendarThree.book(10, 40) # returns 2
myCalendarThree.book(5, 15) # returns 3
myCalendarThree.book(5, 10) # returns 3
myCalendarThree.book(25, 55) # returns 3
โบ
Output:
[1, 1, 2, 3, 3, 3]
๐ก Note:
First booking [10,20) has 1 overlap. Second [50,60) doesn't overlap, still max 1. Third [10,40) overlaps with first, max becomes 2. Fourth [5,15) overlaps with first two during [10,15), making max 3.
example_2.py โ Edge Case with Adjacent Intervals
$
Input:
myCalendarThree = MyCalendarThree()
myCalendarThree.book(1, 2) # returns 1
myCalendarThree.book(2, 3) # returns 1
myCalendarThree.book(1, 3) # returns 2
โบ
Output:
[1, 1, 2]
๐ก Note:
[1,2) and [2,3) don't overlap since intervals are half-open. [1,3) overlaps with both but at different times, so max overlap is 2.
example_3.py โ Same Time Intervals
$
Input:
myCalendarThree = MyCalendarThree()
myCalendarThree.book(5, 10) # returns 1
myCalendarThree.book(5, 10) # returns 2
myCalendarThree.book(5, 10) # returns 3
โบ
Output:
[1, 2, 3]
๐ก Note:
Three identical bookings [5,10) all completely overlap, creating a 3-booking at any time in [5,10).
Constraints
-
0 โค
start<endโค 109 -
At most 400 calls will be made to
book -
Time intervals are half-open:
[start, end)
Visualization
Tap to expand
Understanding the Visualization
1
Add Booking Events
Mark each booking start with +1, each end with -1
2
Sort Time Points
Process all events in chronological order
3
Sweep Timeline
Maintain running count of active bookings
4
Track Maximum
The highest count reached is our k-booking answer
Key Takeaway
๐ฏ Key Insight: Instead of storing all intervals, we only track the net change in overlap count at critical time points, making updates efficient with O(log n) complexity per booking.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code