Skip to content

729. My Calendar I 👍

Approach 1: Brute Force

  • Time: $O(n^2)$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
class MyCalendar {
 public:
  bool book(int start, int end) {
    for (const auto& [s, e] : timeline)
      if (max(start, s) < min(end, e))
        return false;
    timeline.emplace_back(start, end);
    return true;
  }

 private:
  vector<pair<int, int>> timeline;
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
class MyCalendar {
  public boolean book(int start, int end) {
    for (int[] t : timeline)
      if (Math.max(t[0], start) < Math.min(t[1], end))
        return false;
    timeline.add(new int[] {start, end});
    return true;
  }

  private List<int[]> timeline = new ArrayList<>();
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
class MyCalendar:
  def __init__(self):
    self.timeline = []

  def book(self, start: int, end: int) -> bool:
    for s, e in self.timeline:
      if max(start, s) < min(end, e):
        return False
    self.timeline.append((start, end))
    return True

Approach 2: Ordered Map

  • Time: $O(n\log n)$
  • Space: $O(n)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
class MyCalendar {
 public:
  bool book(int start, int end) {
    auto lo = timeline.lower_bound(end);

    if (lo == timeline.begin() || (--lo)->second <= start) {
      timeline[start] = end;
      return true;
    }

    return false;
  }

 private:
  map<int, int> timeline;
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
class MyCalendar {
  public boolean book(int start, int end) {
    Integer low = timeline.lowerKey(end);

    if (low == null || timeline.get(low) <= start) {
      timeline.put(start, end);
      return true;
    }

    return false;
  }

  private TreeMap<Integer, Integer> timeline = new TreeMap<>();
}

Approach 3: Tree

  • Time: $O(n\log n) \to O(n^2)$
  • Space: $O(n)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
from dataclasses import dataclass


@dataclass
class Node:
  start: int
  end: int
  left = None
  right = None


class Tree:
  def __init__(self):
    self.root = None

  def insert(self, node: Node, root: Node = None) -> bool:
    if not root:
      if not self.root:
        self.root = node
        return True
      else:
        root = self.root

    if node.start >= root.end:
      if not root.right:
        root.right = node
        return True
      return self.insert(node, root.right)
    elif node.end <= root.start:
      if not root.left:
        root.left = node
        return True
      return self.insert(node, root.left)
    else:
      return False


class MyCalendar:
  def __init__(self):
    self.tree = Tree()

  def book(self, start: int, end: int) -> bool:
    return self.tree.insert(Node(start, end))