KatInterview

731. My Calendar II

MediumSolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

The problem requires us to implement a MyCalendarTwo class. Its book(startTime, endTime) method should add a new event to a calendar. The key constraint is that an event can only be added if it does not create a "triple booking". A triple booking occurs when three or more events have a common, non-empty time interval of overlap. Double bookings, where exactly two events overlap, are permissible.

Solution

My Calendar II in Python

class MyCalendarTwo:

    def __init__(self):
        # Use a dictionary to store the change in event counts at specific times.
        self.timeline = {}

    def book(self, start: int, end: int) -> bool:
        # Tentatively add the new event's boundaries.
        # Increment at the start time, decrement at the end time.
        self.timeline[start] = self.timeline.get(start, 0) + 1
        self.timeline[end] = self.timeline.get(end, 0) - 1

        active_events = 0
        # Iterate through the timeline points in sorted order to check for triple bookings.
        for time in sorted(self.timeline.keys()):
            active_events += self.timeline[time]
            # If at any point, the number of active events is 3 or more,
            # it's a triple booking.
            if active_events >= 3:
                # The booking is invalid. Revert the changes.
                self.timeline[start] -= 1
                # Clean up dictionary entry if its count becomes zero.
                if self.timeline[start] == 0:
                    del self.timeline[start]
                
                self.timeline[end] += 1
                if self.timeline[end] == 0:
                    del self.timeline[end]
                
                return False
        
        # If the loop completes without finding a triple booking, the booking is valid.
        return True

# Your MyCalendarTwo object will be instantiated and called as such:
# obj = MyCalendarTwo()
# param_1 = obj.book(start,end)

My Calendar II in Java

class MyCalendarTwo {
    // Use a TreeMap to store the change in event counts at specific times.
    // TreeMap keeps keys sorted, which is essential for the sweep-line algorithm.
    private TreeMap<Integer, Integer> timeline;

    public MyCalendarTwo() {
        timeline = new TreeMap<>();
    }
    
    public boolean book(int start, int end) {
        // Tentatively add the new event's boundaries.
        // Increment at the start time, decrement at the end time.
        timeline.put(start, timeline.getOrDefault(start, 0) + 1);
        timeline.put(end, timeline.getOrDefault(end, 0) - 1);

        int activeEvents = 0;
        // Iterate through the timeline to check for triple bookings.
        // The values() of a TreeMap are iterated in key-sorted order.
        for (int delta : timeline.values()) {
            activeEvents += delta;
            // If at any point, the number of active events is 3 or more,
            // it's a triple booking.
            if (activeEvents >= 3) {
                // The booking is invalid. Revert the changes.
                timeline.put(start, timeline.get(start) - 1);
                // Clean up map entry if its count becomes zero.
                if (timeline.get(start) == 0) {
                    timeline.remove(start);
                }
                timeline.put(end, timeline.get(end) + 1);
                if (timeline.get(end) == 0) {
                    timeline.remove(end);
                }
                return false;
            }
        }

        // If the loop completes without finding a triple booking, the booking is valid.
        return true;
    }
}

/**
 * Your MyCalendarTwo object will be instantiated and called as such:
 * MyCalendarTwo obj = new MyCalendarTwo();
 * boolean param_1 = obj.book(start,end);
 */

My Calendar II in C++

class MyCalendarTwo {
private:
    // Use a map to store the change in event counts at specific times.
    // A positive value indicates the start of an event, negative indicates the end.
    std::map<int, int> timeline;

public:
    MyCalendarTwo() {
    }
    
    bool book(int start, int end) {
        // Tentatively add the new event's boundaries.
        // Increment at the start time, decrement at the end time.
        timeline[start]++;
        timeline[end]--;
        
        int active_events = 0;
        // Iterate through the timeline to check for triple bookings.
        for (auto const& [time, delta] : timeline) {
            active_events += delta;
            // If at any point, the number of active events is 3 or more,
            // it's a triple booking.
            if (active_events >= 3) {
                // The booking is invalid. Revert the changes.
                timeline[start]--;
                // Clean up map entry if its count becomes zero.
                if (timeline[start] == 0) {
                    timeline.erase(start);
                }
                timeline[end]++;
                if (timeline[end] == 0) {
                    timeline.erase(end);
                }
                return false;
            }
        }
        
        // If the loop completes without finding a triple booking, the booking is valid.
        return true;
    }
};

/**
 * Your MyCalendarTwo object will be instantiated and called as such:
 * MyCalendarTwo* obj = new MyCalendarTwo();
 * bool param_1 = obj->book(start,end);
 */

My Calendar II in TypeScript

class MyCalendarTwo {
    // Use a Map to store the change in event counts at specific times.
    private timeline: Map<number, number>;

    constructor() {
        this.timeline = new Map<number, number>();
    }

    book(start: number, end: number): boolean {
        // Tentatively add the new event's boundaries.
        // Increment at the start time, decrement at the end time.
        this.timeline.set(start, (this.timeline.get(start) || 0) + 1);
        this.timeline.set(end, (this.timeline.get(end) || 0) - 1);

        let activeEvents = 0;
        // Get the keys, sort them, and iterate to check for triple bookings.
        const sortedTimes = Array.from(this.timeline.keys()).sort((a, b) => a - b);

        for (const time of sortedTimes) {
            // The non-null assertion `!` is safe here because we are iterating over existing keys.
            activeEvents += this.timeline.get(time)!;
            // If at any point, the number of active events is 3 or more,
            // it's a triple booking.
            if (activeEvents >= 3) {
                // The booking is invalid. Revert the changes.
                this.timeline.set(start, this.timeline.get(start)! - 1);
                // Clean up map entry if its count becomes zero.
                if (this.timeline.get(start) === 0) {
                    this.timeline.delete(start);
                }
                this.timeline.set(end, this.timeline.get(end)! + 1);
                if (this.timeline.get(end) === 0) {
                    this.timeline.delete(end);
                }
                return false;
            }
        }

        // If the loop completes without finding a triple booking, the booking is valid.
        return true;
    }
}

/**
 * Your MyCalendarTwo object will be instantiated and called as such:
 * var obj = new MyCalendarTwo()
 * var param_1 = obj.book(start,end)
 */

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.