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

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

PythonSolution
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

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.

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.

Free to download. Check it runs on your machine, then pick a plan.