My Calendar II

medium intervals design sweep line

Problem

Design MyCalendarTwo where book(start, end) adds a half-open interval and returns true only if doing so will never cause a triple booking. Reject the booking otherwise.

Inputbook(10,20); book(50,60); book(10,40); book(5,15)
Output[true, true, true, false]
The fourth booking would create a triple overlap with the first and third.

class MyCalendarTwo:
    def __init__(self):
        self.events = []
        self.overlaps = []
    def book(self, start, end):
        for s, e in self.overlaps:
            if start < e and s < end: return False
        for s, e in self.events:
            if start < e and s < end:
                self.overlaps.append((max(s, start), min(e, end)))
        self.events.append((start, end))
        return True
class MyCalendarTwo {
  constructor() { this.events = []; this.overlaps = []; }
  book(start, end) {
    for (const [s, e] of this.overlaps) if (start < e && s < end) return false;
    for (const [s, e] of this.events) if (start < e && s < end) this.overlaps.push([Math.max(s, start), Math.min(e, end)]);
    this.events.push([start, end]);
    return true;
  }
}
class MyCalendarTwo {
  List<int[]> events = new ArrayList<>(), overlaps = new ArrayList<>();
  public boolean book(int start, int end) {
    for (int[] x : overlaps) if (start < x[1] && x[0] < end) return false;
    for (int[] x : events) if (start < x[1] && x[0] < end)
      overlaps.add(new int[]{Math.max(x[0], start), Math.min(x[1], end)});
    events.add(new int[]{start, end});
    return true;
  }
}
class MyCalendarTwo {
  vector<pair<int,int>> events, overlaps;
public:
  bool book(int start, int end) {
    for (auto& [s, e] : overlaps) if (start < e && s < end) return false;
    for (auto& [s, e] : events) if (start < e && s < end)
      overlaps.push_back({max(s, start), min(e, end)});
    events.push_back({start, end});
    return true;
  }
};
Time: O(n) per booking Space: O(n)