KatInterview

729. My Calendar I

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 MyCalendar class that can book events. An event is represented by a half-open interval [startTime, endTime). A new event can only be booked if it does not overlap with any previously booked events. This is what's called avoiding a "double booking". The core of the problem is to efficiently store the booked events and check for overlaps with any new event.

Solution

My Calendar I in Python

class MyCalendar:

    def __init__(self):
        # Store events in a simple list.
        self.calendar = []

    def book(self, startTime: int, endTime: int) -> bool:
        # Iterate through all existing bookings to check for overlaps.
        for s, e in self.calendar:
            # Two intervals [s1, e1) and [s2, e2) overlap if s1 < e2 and s2 < e1.
            # Here, s1=s, e1=e and s2=startTime, e2=endTime.
            # So we check if s < endTime and startTime < e.
            if startTime < e and s < endTime:
                return False
        
        # If no overlaps are found, add the new event to the calendar.
        self.calendar.append([startTime, endTime])
        return True


# Your MyCalendar object will be instantiated and called as such:
# obj = MyCalendar()
# param_1 = obj.book(startTime,endTime)

My Calendar I in Java

class MyCalendar {
    // Use a TreeMap to store events, sorted by start time.
    // Key: startTime, Value: endTime
    private TreeMap<Integer, Integer> calendar;

    public MyCalendar() {
        calendar = new TreeMap<>();
    }
    
    public boolean book(int startTime, int endTime) {
        // Find the event with the greatest start time less than or equal to startTime.
        Map.Entry<Integer, Integer> prev = calendar.floorEntry(startTime);
        // If such an event exists and its end time is after the new event's start time, there's an overlap.
        // e.g., new=[15,25), prev=[10,20). 15 < 20, so overlap.
        if (prev != null && prev.getValue() > startTime) {
            return false;
        }

        // Find the event with the smallest start time greater than or equal to startTime.
        Map.Entry<Integer, Integer> next = calendar.ceilingEntry(startTime);
        // If such an event exists and its start time is before the new event's end time, there's an overlap.
        // e.g., new=[15,25), next=[20,30). 25 > 20, so overlap.
        if (next != null && next.getKey() < endTime) {
            return false;
        }

        // No overlaps, so book the event and return true.
        calendar.put(startTime, endTime);
        return true;
    }
}

/**
 * Your MyCalendar object will be instantiated and called as such:
 * MyCalendar obj = new MyCalendar();
 * boolean param_1 = obj.book(startTime,endTime);
 */

My Calendar I in C++

class MyCalendar {
private:
    // Use a map to store events, sorted by start time.
    // Key: startTime, Value: endTime
    std::map<int, int> calendar;

public:
    MyCalendar() {
        
    }
    
    bool book(int startTime, int endTime) {
        // Find the first event that starts at or after startTime.
        auto it = calendar.lower_bound(startTime);

        // Check for overlap with the next event.
        // If an event `it` exists and its start time is before the new event's end time, they overlap.
        // [startTime, endTime) vs [it->first, it->second)
        // Overlap if it->first < endTime
        if (it != calendar.end() && it->first < endTime) {
            return false;
        }

        // Check for overlap with the previous event.
        // `it` points to the first event with start >= startTime. The event before `it` is the one
        // with the largest start time smaller than startTime.
        if (it != calendar.begin()) {
            auto prev_it = std::prev(it);
            // [startTime, endTime) vs [prev_it->first, prev_it->second)
            // Overlap if startTime < prev_it->second
            if (prev_it->second > startTime) {
                return false;
            }
        }

        // No overlaps, so book the event and return true.
        calendar[startTime] = endTime;
        return true;
    }
};

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

My Calendar I in TypeScript

class MyCalendar {
    private calendar: [number, number][];

    constructor() {
        // Store events in a simple array.
        this.calendar = [];
    }

    book(startTime: number, endTime: number): boolean {
        // Iterate through all existing bookings to check for overlaps.
        for (const [s, e] of this.calendar) {
            // Two intervals [s1, e1) and [s2, e2) overlap if s1 < e2 and s2 < e1.
            // Here, s1=s, e1=e and s2=startTime, e2=endTime.
            // So we check if s < endTime and startTime < e.
            if (startTime < e && s < endTime) {
                return false;
            }
        }

        // If no overlaps are found, add the new event to the calendar.
        this.calendar.push([startTime, endTime]);
        return true;
    }
}

/**
 * Your MyCalendar object will be instantiated and called as such:
 * var obj = new MyCalendar()
 * var param_1 = obj.book(startTime,endTime)
 */

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.