Skip to main content

My Calendar III - Solution & Explanation

HardBinary SearchDesignSegment TreePrefix Sum18 min readAsked at: Google
Practice this problem

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 integer k representing the largest integer such that there exists a k-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 400 calls will be made to book.

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.

Try this approach in the editor →

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.

Code

C#

C++

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.

Try this approach in the editor →

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], where mid = \lfloor(l + r) / 2\rfloor (i.e., floor division).

For this problem, the segment tree nodes maintain the following information:

  1. The maximum number of times the interval has been booked, v.
  2. 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

Try this approach in the editor →

Complexity Comparison

ApproachComplexity
Sweep Line Approach

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.

Balanced Tree Map Approach

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.

Segment Tree—

Detailed Complexity Analysis

ApproachTimeSpaceWhen to Use
Sweep Line with Difference MapO(n) per bookingO(n)Best for moderate constraints where simplicity and clarity matter
Balanced Tree Map (Ordered Map)O(n) per booking, O(log n) updateO(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 is classified as a Hard problem on LeetCode. The challenge comes from designing a data structure that dynamically tracks overlapping intervals while returning the maximum concurrency after each booking.
My Calendar III Python/Java solution
Python and Java implementations usually rely on a sweep line technique with a sorted dictionary or TreeMap. Each booking updates start and end deltas, and iterating through the map calculates the maximum overlap after every insertion.
How to solve My Calendar III in O(n)?
Maintain a map of time points where starts add +1 and ends add -1. After inserting the changes for a booking, iterate through the sorted keys and maintain a running prefix sum to compute active events. Track the maximum value during the sweep and return it as the current k-booking.
What is the best approach for My Calendar III?
The most common solution uses a sweep line with a difference map. Each booking adds +1 at the start time and -1 at the end time, then a prefix sum scan finds the maximum overlap. This approach runs in O(n) time per booking with O(n) space and is widely used in interview solutions.
Is My Calendar III asked at Google/Amazon/Meta?
My Calendar problems are common interval design questions and have appeared in interviews at companies like Google, Amazon, and Meta. They test understanding of interval overlap, sweep line techniques, and ordered data structures.
What data structure is used in My Calendar III?
Most implementations use an ordered map such as TreeMap or std::map to maintain sorted time points. The algorithm also relies on a prefix sum sweep across these keys to compute active overlaps.
What is the time complexity of My Calendar III?
The typical sweep line implementation takes O(n) time per booking because the algorithm scans all stored time points to compute the running overlap. Updating the ordered map itself costs O(log n), but the prefix traversal dominates the complexity.

Ready to solve this problem?

Practice My Calendar III with our built-in code editor and test cases.

Practice on FleetCode