My Calendar III

This page explains Java solution to problem My Calendar III using TreeMap data structure.

Problem Statement

Implement a MyCalendarIii class to store your events. A new event can always be added.

Your class will have one method, book(int start, int end). Formally, this represents a booking on the half open interval [start, end), the range of real numbers x such that start

A K-booking happens when K events have some non-empty intersection (ie., there is some time that is common to all K events.)

For each call to the method, return an integer K representing the largest integer such that there exists a K-booking in the calendar.

Example 1:

MyCalendarThree();, 20); // returns 1, 60); // returns 1, 40); // returns 2, 15); // returns 3, 10); // returns 3, 55); // returns 3
The first two events can be booked and are disjoint, so the maximum K-booking is a 1-booking.
The third event [10, 40) intersects the first event, and the maximum K-booking is a 2-booking.
The remaining events cause the maximum K-booking to be only a 3-booking.
Note that the last event locally causes a 2-booking, but the answer is still 3 because
eg. [10, 20), [10, 40), and [5, 15) are still triple booked.

Example 2:

Input: A = [1,2], B = [3,4]
Output: 2.50000
Explanation: merged array = [1,2,3,4] and median is (2 + 3) / 2 = 2.5


If you have any suggestions in below code, please create a pull request by clicking here.


import java.util.*;

class MyCalendarIii {
    private TreeMap<Integer, Integer> map;
    public MyCalendarIii() {
        map = new TreeMap<>();

    public int book(int start, int end) {
        map.put(start, map.getOrDefault(start, 0) + 1);
        map.put(end, map.getOrDefault(end, 0) - 1);

        int ongoing = 0;
        int res = 0;
        for(Map.Entry<Integer, Integer> entry: map.entrySet()) {
            ongoing += entry.getValue();
            res = Math.max(ongoing, res);
        return res;

 * Your MyCalendarThree object will be instantiated and called as such:
 * MyCalendarIii obj = new MyCalendarIii();
 * int param_1 =,end);

Time Complexity

O(N2) Where
N is total number of bookings

Space Complexity

O(N) Where
N is total number of bookings