My Calendar III - Solution & Explanation
Problem Statement
A k-booking happens when k events have some non-empty intersection (i.e., there is some time that is common to all k events.)
You are given some events [startTime, endTime), after each given event, return an integer k representing the maximum k-booking between all the previous events.
Implement the MyCalendarThree class:
MyCalendarThree()Initializes the object.int book(int startTime, int endTime)Returns an integerkrepresenting the largest integer such that there exists ak-booking in the calendar.
Example 1:
Input ["MyCalendarThree", "book", "book", "book", "book", "book", "book"] [[], [10, 20], [50, 60], [10, 40], [5, 15], [5, 10], [25, 55]] Output [null, 1, 1, 2, 3, 3, 3] Explanation MyCalendarThree myCalendarThree = new MyCalendarThree(); myCalendarThree.book(10, 20); // return 1 myCalendarThree.book(50, 60); // return 1 myCalendarThree.book(10, 40); // return 2 myCalendarThree.book(5, 15); // return 3 myCalendarThree.book(5, 10); // return 3 myCalendarThree.book(25, 55); // return 3
Constraints:
0 <= startTime < endTime <= 109- At most
400calls will be made tobook.
Approach Overview
Problem Overview: Design a booking system where each event is an interval [start, end). After every booking, return the maximum number of overlapping events (k-booking) seen so far. The challenge is efficiently tracking overlaps as intervals are inserted one by one.
Approach 1: Sweep Line with Difference Map (O(n) per booking, O(n) space)
This method treats every interval as two events: +1 at start and -1 at end. Store these changes in an ordered structure and perform a prefix scan to compute active overlaps. Each time you book an event, increment the start position and decrement the end position, then iterate through the timeline accumulating the running sum. The maximum prefix value represents the highest number of concurrent events. This is a classic prefix sum style sweep that simulates a timeline of events.
The key insight: overlapping intervals translate into cumulative counts. When multiple events start before previous ones end, the prefix sum naturally grows. This approach is simple to implement and works well for the constraint size of the problem.
Approach 2: Balanced Tree Map (Ordered Map Sweep) (O(n) per booking, O(n) space)
Use a balanced ordered map (such as TreeMap or std::map) to store time points and their delta changes. Insert +1 at the start and -1 at the end of each interval. Because the structure keeps keys sorted, you can iterate through the map to compute the running prefix sum and track the maximum overlap. The ordered structure ensures updates happen in O(log n), while the sweep to compute the maximum takes O(n).
This approach is essentially a structured version of the sweep line technique often used in interval problems and computational geometry. Using an ordered set / map guarantees sorted traversal without extra sorting overhead.
For larger-scale versions of this problem, advanced solutions rely on a dynamic segment tree to track range updates and maximum overlaps in O(log n). That structure is more complex but scales better when the number of bookings becomes very large.
Recommended for interviews: The sweep line with an ordered map is the expected solution. It shows clear understanding of interval overlap problems and prefix accumulation. Explaining the difference-array idea demonstrates strong algorithmic intuition, while mentioning a segment tree extension shows awareness of scalable designs.
Approach 1: Sweep Line Approach
This method uses a line sweep technique, where we process the critical points along the time axis. We treat each event start time as a +1 (which indicates a new event starts), and each end time as a -1 (indicating an event ends).
By maintaining a running sum, we can identify the maximum overlap of events, which gives us the maximum k-booking at any point.
In this Python implementation, we maintain a list of tuples representing time points and their effects (+1 or -1). We sort these time points and iterate over them to calculate the maximum overlapping intervals, thus obtaining the maximum k-booking.
Code
Python
Java
JavaScript
Complexity
Time Complexity: O(N log N) due to sorting.
Space Complexity: O(N) for storing the timeline of events, where N is the number of events booked.
Approach 2: Balanced Tree Map Approach
A more advanced approach involves using a balanced tree map (or balanced tree data structure) to manage events and efficiently find the maximum overlap.
The map holds start and end times as keys and their occurrences as values. By efficiently summing these up, we can determine the maximum k-booking.
This C# solution uses a SortedDictionary to act like a balanced binary search tree. We increment the value for a start time and decrement for an end time. The running sum of values reflects the number of active events at any time.
Complexity
Time Complexity: O(N log N) for the operations on a balanced tree.
Space Complexity: O(N) traversing the sorted keys when booking new events.
Approach 3: Segment Tree
A segment tree divides the entire interval into multiple non-contiguous subintervals, with the number of subintervals not exceeding log(width). To update the value of an element, we only need to update log(width) intervals, and these intervals are all contained within a larger interval that includes the element. When modifying intervals, we use lazy propagation to ensure efficiency.
- Each node of the segment tree represents an interval.
- The segment tree has a unique root node representing the entire range, such as
[1, N]. - Each leaf node of the segment tree represents a unit interval of length
1,[x, x]. - For each internal node
[l, r], its left child is[l, mid]and its right child is[mid + 1, r], wheremid = \lfloor(l + r) / 2\rfloor(i.e., floor division).
For this problem, the segment tree nodes maintain the following information:
- The maximum number of times the interval has been booked,
v. - Lazy propagation marker,
add.
Since the time range is 10^9, which is very large, we use dynamic node creation.
The time complexity is O(n times log n), and the space complexity is O(n), where n is the number of bookings.
Code
Python
Java
C++
Go
TypeScript
Complexity Comparison
| Approach | Complexity |
|---|---|
| Sweep Line Approach | Time Complexity: O(N log N) due to sorting. |
| Balanced Tree Map Approach | Time Complexity: O(N log N) for the operations on a balanced tree. |
| Segment Tree | — |
Detailed Complexity Analysis
| Approach | Time | Space | When to Use |
|---|---|---|---|
| Sweep Line with Difference Map | O(n) per booking | O(n) | Best for moderate constraints where simplicity and clarity matter |
| Balanced Tree Map (Ordered Map) | O(n) per booking, O(log n) update | O(n) | Preferred in languages with built-in ordered maps like C++ or C# |
Video Solution
Mastering LeetCode's Hardest Problems in 30 Days or Less! | 'My Calendar III' (Problem 732) • HustlerCoder • 8,012 views views
Watch 9 more video solutions →Frequently Asked Questions
Is My Calendar III easy or hard?
My Calendar III Python/Java solution
How to solve My Calendar III in O(n)?
What is the best approach for My Calendar III?
Is My Calendar III asked at Google/Amazon/Meta?
What data structure is used in My Calendar III?
What is the time complexity of My Calendar III?
Ready to solve this problem?
Practice My Calendar III with our built-in code editor and test cases.
Practice on FleetCode