sagelearnai

My Calendar I

Difficulty: Medium · Pattern: Intervals · LeetCode #729

Implement MyCalendar.book(start, end) for the half-open interval [start, end). Add the event and return true if it doesn't overlap any existing booking. Otherwise return false and don't add it.

Example

text
book(10, 20) → true
book(15, 25) → false
book(20, 30) → true    (touching at 20 is fine: half-open)

Hints

  1. Two half-open intervals [s1,e1) and [s2,e2) overlap if and only if s1 < e2 and s2 < e1.
  2. With bookings kept sorted, only the neighbors of the new event's position can conflict.

Approach

Simple O(n) per call: check the new interval against every booking with the overlap test.

O(log n) per call: keep the bookings sorted by start (a balanced BST or SortedList; in plain Python, bisect on a list gives an O(log n) search but O(n) insertion). Find the insertion point and check only the previous booking (its end must be ≤ start) and the next one (its start must be ≥ end).

The overlap condition is worth memorizing. It's the negation of "one ends before the other starts".

Complexity

Time: O(log n) search + O(n) insert (O(n) per call for the scan). Space: O(n).

Python solution
import bisect

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

    def book(self, start, end):
        i = bisect.bisect_right(self.starts, start)
        if i > 0 and self.ends[i - 1] > start:
            return False
        if i < len(self.starts) and self.starts[i] < end:
            return False
        self.starts.insert(i, start)
        self.ends.insert(i, end)
        return True
JavaScript solution
class MyCalendar {
  constructor() { this.events = []; }
  book(start, end) {
    for (const [s, e] of this.events) if (start < e && s < end) return false;
    this.events.push([start, end]);
    return true;
  }
}