MediumNo. 0729
My Calendar I — LeetCode 729 Python Solution
- Pattern
- Monotonic Stack
- Topics
- Design, Segment Tree, Array, Binary Search, Ordered Set
- Reading time
- 3 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 double booking.
Example
- Input
- ["MyCalendar", "book", "book", "book"]
- Output
- [null, true, false, true]
- Explanation
- MyCalendar myCalendar = new MyCalendar();
Python solution
class MyCalendar:
def __init__(self):
self.sd = SortedDict()
def book(self, start: int, end: int) -> bool:
idx = self.sd.bisect_right(start)
if idx < len(self.sd) and self.sd.values()[idx] < end:
return False
self.sd[end] = start
return True
# Your MyCalendar object will be instantiated and called as such:
# obj = MyCalendar()
# param_1 = obj.book(start,end)Complexity
- Time
- O(n × log n)
- Space · auxiliary
- O(n)
Pattern: Monotonic Stack
Answer "what is the next greater element" for every position in one pass. LeetCode 729. My Calendar I is filed here because the reference solution below belongs to the algorithm family this hub collects, even though its LeetCode tags point elsewhere.
The monotonic stack guide has the Python template for the pattern and the 225 LeetCode problems that use it.
Related problems
| No. | Problem | Difficulty |
|---|---|---|
| 0731 | My Calendar II | Medium |
| 0732 | My Calendar III | Hard |
| 0315 | Count of Smaller Numbers After Self | Hard |
| 0327 | Count of Range Sum | Hard |
| 0493 | Reverse Pairs | Hard |
| 1157 | Online Majority Element In Subarray | Hard |
Frequently asked questions
- How hard is LeetCode 729. My Calendar I?
LeetCode 729. My Calendar I is rated Medium on LeetCode.
- What is the time complexity of LeetCode 729. My Calendar I?
The Python solution on this page runs in O(n × log n).
- What is the space complexity of LeetCode 729. My Calendar I?
The Python solution on this page uses O(n) auxiliary space.
- What topics does LeetCode 729. My Calendar I cover?
LeetCode 729. My Calendar I is tagged Design, Segment Tree, Array, Binary Search and Ordered Set on LeetCode.