My Calendar I

medium intervals binary search ordered set design

Problem

Design a MyCalendar that records events as half-open intervals [start, end). The book(start, end) call should add the event and return true only if it does not overlap any previously booked event.

Inputbook(10,20); book(15,25); book(20,30)
Output[true, false, true]
The second booking overlaps [10,20); the third only touches at 20 which is allowed.

from sortedcontainers import SortedList
class MyCalendar:
    def __init__(self):
        self.starts = SortedList()
        self.book_map = {}
    def book(self, start, end):
        i = self.starts.bisect_right(start)
        if i > 0 and self.book_map[self.starts[i-1]] > start: return False
        if i < len(self.starts) and self.starts[i] < end: return False
        self.starts.add(start); self.book_map[start] = end
        return True
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;
  }
}
class MyCalendar {
  TreeMap<Integer,Integer> map = new TreeMap<>();
  public boolean book(int start, int end) {
    Integer prev = map.floorKey(start), next = map.ceilingKey(start);
    if (prev != null && map.get(prev) > start) return false;
    if (next != null && next < end) return false;
    map.put(start, end);
    return true;
  }
}
class MyCalendar {
  map<int,int> mp;
public:
  bool book(int start, int end) {
    auto it = mp.lower_bound(start);
    if (it != mp.end() && it->first < end) return false;
    if (it != mp.begin() && prev(it)->second > start) return false;
    mp[start] = end;
    return true;
  }
};
Time: O(log n) per booking Space: O(n)