My Calendar III

hard intervals sweep line ordered map design

Problem

Design MyCalendarThree where book(start, end) records an event and returns the maximum k-booking (largest number of mutually overlapping events) across the calendar so far.

Inputbook(10,20); book(50,60); book(10,40); book(5,15)
Output[1, 1, 2, 3]
After the fourth booking, three events all contain time 10..15.

from sortedcontainers import SortedDict
class MyCalendarThree:
    def __init__(self):
        self.delta = SortedDict()
    def book(self, start, end):
        self.delta[start] = self.delta.get(start, 0) + 1
        self.delta[end] = self.delta.get(end, 0) - 1
        active = best = 0
        for v in self.delta.values():
            active += v
            if active > best: best = active
        return best
class MyCalendarThree {
  constructor() { this.delta = new Map(); }
  book(start, end) {
    this.delta.set(start, (this.delta.get(start) || 0) + 1);
    this.delta.set(end, (this.delta.get(end) || 0) - 1);
    const keys = [...this.delta.keys()].sort((a, b) => a - b);
    let active = 0, best = 0;
    for (const k of keys) { active += this.delta.get(k); if (active > best) best = active; }
    return best;
  }
}
class MyCalendarThree {
  TreeMap<Integer,Integer> delta = new TreeMap<>();
  public int book(int start, int end) {
    delta.merge(start, 1, Integer::sum);
    delta.merge(end, -1, Integer::sum);
    int active = 0, best = 0;
    for (int v : delta.values()) { active += v; if (active > best) best = active; }
    return best;
  }
}
class MyCalendarThree {
  map<int,int> delta;
public:
  int book(int start, int end) {
    delta[start]++; delta[end]--;
    int active = 0, best = 0;
    for (auto& [_, v] : delta) { active += v; if (active > best) best = active; }
    return best;
  }
};
Time: O(n) per booking Space: O(n)