#729
My Calendar I
MediumArrayBinary SearchDesignSegment TreeOrdered SetBinary SearchArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n log n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n log n)Space O(n)
By storing the bookings in a sorted list, we can use binary search to efficiently find the position where the new booking would fit, allowing us to check for overlaps quickly.
⚙️
Algorithm
3 steps- 1Step 1: Initialize an empty list to store booked events.
- 2Step 2: For each new booking request, use binary search to find the correct position to insert the new booking.
- 3Step 3: Check the adjacent bookings to see if there is an overlap. If there is no overlap, insert the new booking and return true; otherwise, return false.
solution.py14 lines
1import bisect
2
3class MyCalendar:
4 def __init__(self):
5 self.bookings = []
6
7 def book(self, startTime: int, endTime: int) -> bool:
8 i = bisect.bisect_left(self.bookings, (startTime, endTime))
9 if i > 0 and self.bookings[i - 1][1] > startTime:
10 return False
11 if i < len(self.bookings) and self.bookings[i][0] < endTime:
12 return False
13 self.bookings.insert(i, (startTime, endTime))
14 return Trueℹ
Complexity note: The time complexity is O(n log n) due to the binary search for insertion, while space complexity is O(n) for storing the bookings.
- 1Using binary search can significantly reduce the time complexity of checking for overlaps.
- 2Storing intervals in a sorted manner allows for efficient insertion and overlap checking.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.