Greedy Algorithms8 sections · 316 units
Open in Course

My Calendar I - Implementation

The code

Here is the simple solution:

class MyCalendar
 bookings := []

 function book(start, end)
 for each (s, e) in bookings
 if start < e and s < end then
 return false
 bookings.add((start, end))
 return true

Two intervals [s1,e1)[s_1, e_1) and [s2,e2)[s_2, e_2) overlap if and only if s1<e2s_1 < e_2 and s2<e1s_2 < e_1. This is the standard overlap check.

Time: O(n)O(n) per booking. Space: O(n)O(n) total.