> ## Documentation Index
> Fetch the complete documentation index at: https://leetcode-py.wisl.dev/llms.txt
> Use this file to discover all available pages before exploring further.

> ## Agent Instructions
> leetcode-py is a Python LeetCode practice environment generator with one CLI: lcpy. It is not a service or platform.
> Each problem is a directory under leetcode/ with README.md, solution.py, test_solution.py, helpers.py, and playground.ipynb. lcpy gen creates them from JSON templates bundled with the package.
> Examples are backed by tests; copy them verbatim.

# My Calendar II Python Solution with Tests

> Tested Python solution for LeetCode 731 with 12 pytest cases. Generate a practice environment with lcpy.

LeetCode 731, [Medium](/catalog/medium). Topics: [Array](/catalog/topics/array), [Binary Search](/catalog/topics/binary-search), [Design](/catalog/topics/design), [Segment Tree](/catalog/topics/segment-tree), [Ordered Set](/catalog/topics/ordered-set), [Prefix Sum](/catalog/topics/prefix-sum). [View on LeetCode](https://leetcode.com/problems/my-calendar-ii/description/).

Generate this problem as a practice environment: tested reference solution, 12 [parametrized pytest cases](/practice/testing), and a playground notebook:

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
lcpy gen -n 731   # by problem number
lcpy gen -s my_calendar_ii   # by problem name
```

## 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.

A triple booking happens when three events have some non-empty intersection (i.e., some moment is common to all the three events.).

The event can be represented as a pair of integers `startTime` and `endTime` that represents a booking on the half-open interval `[startTime, endTime)`, the range of real numbers `x` such that `startTime <= x < endTime`.

Implement the `MyCalendarTwo` class:

* `MyCalendarTwo()` Initializes the calendar object.
* `boolean book(int startTime, int endTime)` Returns `true` if the event can be added to the calendar successfully without causing a triple booking. Otherwise, return `false` and do not add the event to the calendar.

### Examples

```
Input
["MyCalendarTwo", "book", "book", "book", "book", "book", "book"]
[[], [10, 20], [50, 60], [10, 40], [5, 15], [5, 10], [25, 55]]
Output
[null, true, true, true, false, true, true]

Explanation
MyCalendarTwo myCalendarTwo = new MyCalendarTwo();
myCalendarTwo.book(10, 20); // return True, The event can be booked.
myCalendarTwo.book(50, 60); // return True, The event can be booked.
myCalendarTwo.book(10, 40); // return True, The event can be double booked.
myCalendarTwo.book(5, 15);  // return False, The event cannot be booked, because it would result in a triple booking.
myCalendarTwo.book(5, 10);  // return True, The event can be booked, as it does not use time 10 which is already double booked.
myCalendarTwo.book(25, 55); // return True, The event can be booked, as the time in [25, 40) will be double booked with the third event;
                            // the time [40, 50) will be single booked, and the time [50, 55) will be double booked with the second event.
```

### Constraints

* 0 \<= start \< end \<= 10^9
* At most 1000 calls will be made to book.

## Solution

Reference implementation from [solution.py on GitHub](https://github.com/wislertt/leetcode-py/blob/main/leetcode/my_calendar_ii/solution.py), full suite in [test\_solution.py](https://github.com/wislertt/leetcode-py/blob/main/leetcode/my_calendar_ii/test_solution.py):

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
class MyCalendarTwo:
    # Tracks single and double bookings; a new event is valid iff it
    # overlaps no double-booked region.
    # Time: O(n) per book
    # Space: O(n)
    def __init__(self) -> None:
        self._booked: list[tuple[int, int]] = []
        self._double_booked: list[tuple[int, int]] = []

    @staticmethod
    def _intersects(s1: int, e1: int, s2: int, e2: int) -> bool:
        return max(s1, s2) < min(e1, e2)

    def book(self, start_time: int, end_time: int) -> bool:
        if any(self._intersects(start_time, end_time, s, e) for s, e in self._double_booked):
            return False
        for s, e in self._booked:
            if self._intersects(start_time, end_time, s, e):
                self._double_booked.append((max(start_time, s), min(end_time, e)))
        self._booked.append((start_time, end_time))
        return True
```

## Complexity

| Time | Space |
| - | - |
| O(n) per book | O(n) |

## Tags

[NeetCode All](/catalog/neetcode).


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.