My Calendar I — LeetCode 729 Python Solution

MediumDesignSegment TreeArrayBinary SearchOrdered Set
Problem
#729
Reading time
3 min

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

Python
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

MeasureComplexity
TimeO(n \times \log n)
SpaceO(n) auxiliary

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

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 \times \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.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview