729. My Calendar I
Problem
Design MyCalendar whose book(start, end) adds the event [start, end) and returns true if it doesn't overlap any booked event; otherwise it books nothing and returns false.
Example: book(10,20) → true, book(15,25) → false, book(20,30) → true
Constraints: up to 1000 calls.
Keep booked intervals sorted by start. A new [s, e) is fine iff it ends before the next booking starts and starts after the previous booking ends — one binary search (Java TreeMap.floorKey/ceilingKey).
Complexity: O(log n) per booking (O(n) insert for a Python list).
class MyCalendar:
def __init__(self):
self.starts, self.ends = [], []
def book(self, start: int, end: int) -> bool:
i = bisect.bisect_right(self.starts, start)
if i > 0 and self.ends[i - 1] > start: # previous overlaps
return False
if i < len(self.starts) and self.starts[i] < end: # next overlaps
return False
self.starts.insert(i, start)
self.ends.insert(i, end)
return True
c = MyCalendar()
assert [c.book(10, 20), c.book(15, 25), c.book(20, 30)] == [True, False, True]
c2 = MyCalendar()
assert [c2.book(5, 10), c2.book(10, 15), c2.book(9, 11), c2.book(0, 5), c2.book(4, 6)] == [True, True, False, True, False]
class MyCalendar {
private final TreeMap<Integer, Integer> cal = new TreeMap<>(); // start -> end
public boolean book(int start, int end) {
Integer prev = cal.floorKey(start), next = cal.ceilingKey(start);
if (prev != null && cal.get(prev) > start) return false;
if (next != null && next < end) return false;
cal.put(start, end);
return true;
}
}
type MyCalendar struct {
starts, ends []int // bookings sorted by start, never overlapping
}
func Constructor() MyCalendar {
return MyCalendar{}
}
func (this *MyCalendar) Book(start int, end int) bool {
i := sort.SearchInts(this.starts, start+1) // first booking starting after `start`
if i > 0 && this.ends[i-1] > start { // the previous one runs into us
return false
}
if i < len(this.starts) && this.starts[i] < end { // we run into the next one
return false
}
this.starts = insertAt(this.starts, i, start)
this.ends = insertAt(this.ends, i, end)
return true
}
func insertAt(s []int, i, v int) []int {
s = append(s, 0)
copy(s[i+1:], s[i:])
s[i] = v
return s
}