SDE & MLE Prep

729. My Calendar I

Problem

Design MyCalendar whose book(start, end) adds the event [start, end) and returns true if it doesn't overlap any booked event; otherwise it books nothing and returns false.

Example: book(10,20) → true, book(15,25) → false, book(20,30) → true

Constraints: up to 1000 calls.

Keep booked intervals sorted by start. A new [s, e) is fine iff it ends before the next booking starts and starts after the previous booking ends — one binary search (Java TreeMap.floorKey/ceilingKey).

Complexity: O(log n) per booking (O(n) insert for a Python list).

class MyCalendar:
    def __init__(self):
        self.starts, self.ends = [], []

    def book(self, start: int, end: int) -> bool:
        i = bisect.bisect_right(self.starts, start)
        if i > 0 and self.ends[i - 1] > start:          # previous overlaps
            return False
        if i < len(self.starts) and self.starts[i] < end:   # next overlaps
            return False
        self.starts.insert(i, start)
        self.ends.insert(i, end)
        return True