You are implementing a program to manage a calendar of events. Each event is defined by two integers: a start time and an end time. Implement the MyCalendar
class:
MyCalendar()
: Initializes the calendar object.bool book(int start, int end)
: Attempts to book an event from start
to end
(exclusive). If there is no conflicting event that overlaps with this time range, the event can be booked and the method returns True
. Otherwise, the method returns False
.start
and end
?
start
and end
is not explicitly stated but will likely be within a manageable size for memory and computational purposes.To solve this problem, we’ll keep a list to store the intervals of the booked events. For each new booking, we will:
start < booked_event_end
and end > booked_event_start
.False
.True
.This approach ensures that we accurately manage overlapping events while maintaining the simplicity.
class MyCalendar:
def __init__(self):
# Initialize the list to store booked intervals
self.booked = []
def book(self, start: int, end: int) -> bool:
# Check for overlap with existing bookings
for s, e in self.booked:
if start < e and end > s:
return False
# If no overlap, book the event
self.booked.append((start, end))
return True
book
call is O(n)
in worst case, where n
is the number of currently booked events. This is because we need to check every existing booking for potential overlaps.O(n)
since we store each booking.Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?