MediumNo. 0731
My Calendar II — LeetCode 731 Python Solution
- Pattern
- Prefix Sum
- Topics
- Design, Segment Tree, Array, Binary Search, Ordered Set, Prefix Sum
- Reading time
- 4 min
- Source
- leetcode.com
The problem
You are implementing a program to use as your calendar. We can add a new event if adding the event will not cause a triple booking.
Example
- Input
- ["MyCalendarTwo", "book", "book", "book", "book", "book", "book"]
- Output
- [null, true, true, true, false, true, true]
- Explanation
- MyCalendarTwo myCalendarTwo = new MyCalendarTwo();
Python solution
class MyCalendarTwo:
def __init__(self):
self.sd = SortedDict()
def book(self, startTime: int, endTime: int) -> bool:
self.sd[startTime] = self.sd.get(startTime, 0) + 1
self.sd[endTime] = self.sd.get(endTime, 0) - 1
s = 0
for v in self.sd.values():
s += v
if s > 2:
self.sd[startTime] -= 1
self.sd[endTime] += 1
return False
return True
# Your MyCalendarTwo object will be instantiated and called as such:
# obj = MyCalendarTwo()
# param_1 = obj.book(startTime,endTime)Complexity
- Time
- O(n2)
- Space · auxiliary
- O(n)where n is the number of bookings
Pattern: Prefix Sum
Precompute running totals once so any range query becomes a single subtraction. LeetCode 731. My Calendar II is filed here because LeetCode tags it Prefix Sum, which is the vocabulary this hub collects.
The prefix sum guide has the Python template for the pattern and the 157 LeetCode problems that use it.
Related problems
| No. | Problem | Difficulty |
|---|---|---|
| 0732 | My Calendar III | Hard |
| 0729 | My Calendar I | Medium |
| 0315 | Count of Smaller Numbers After Self | Hard |
| 0327 | Count of Range Sum | Hard |
| 0363 | Max Sum of Rectangle No Larger Than K | Hard |
| 0493 | Reverse Pairs | Hard |
Frequently asked questions
- How hard is LeetCode 731. My Calendar II?
LeetCode 731. My Calendar II is rated Medium on LeetCode.
- What is the time complexity of LeetCode 731. My Calendar II?
The Python solution on this page runs in O(n2).
- What is the space complexity of LeetCode 731. My Calendar II?
The Python solution on this page uses O(n), where n is the number of bookings auxiliary space.
- What topics does LeetCode 731. My Calendar II cover?
LeetCode 731. My Calendar II is tagged Design, Segment Tree, Array, Binary Search, Ordered Set and Prefix Sum on LeetCode.