# My Calendar II

Implement a`MyCalendarTwo`class to store your events. A new event can be added if adding the event will not cause a**triple**booking.

Your class will have one method,`book(int start, int end)`. Formally, this represents a booking on the half open interval`[start, end)`, the range of real numbers`x`such that`start <= x < end`.

Atriple bookinghappens when**three**events have some non-empty intersection (ie., there is some time that is common to all 3 events.)

For each call to the method`MyCalendar.book`, return`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.

Your class will be called like this:

`MyCalendar cal = new MyCalendar();`

`MyCalendar.book(start, end)`

**Example 1:**

```
MyCalendar();
MyCalendar.book(10, 20); // returns true
MyCalendar.book(50, 60); // returns true
MyCalendar.book(10, 40); // returns true
MyCalendar.book(5, 15); // returns false
MyCalendar.book(5, 10); // returns true
MyCalendar.book(25, 55); // returns true

Explanation:

The first two events can be booked.  The third event can be double booked.
The fourth event (5, 15) can't be booked, because it would result in a triple booking.
The fifth event (5, 10) can be booked, as it does not use time 10 which is already double booked.
The sixth event (25, 55) 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.
```

**Note:**

* The number of calls to `MyCalendar.book` per test case will be at most `1000`.
* In calls to `MyCalendar.book(start, end)`, `start` and `end` are integers in the range `[0, 10^9]`.

## Solution & Analysis

### Approach #1: Brute Force <a href="#approach-1-brute-force-accepted" id="approach-1-brute-force-accepted"></a>

Maintain a list of bookings and a list of double bookings. When booking a new event `[start, end)`, if it conflicts with a double booking, it will have a triple booking and be invalid. Otherwise, parts that overlap the calendar will be a double booking.

Evidently, two events`[s1, e1)`and`[s2, e2)`do\_not\_conflict if and only if one of them starts after the other one ends: either`e1 <= s2`OR`e2 <= s1`. By De Morgan's laws, this means the events conflict when`s1 < e2`AND`s2 < e1`.

If our event conflicts with a double booking, it's invalid. Otherwise, we add conflicts with the calendar to our double bookings, and add the event to our calendar.

128 ms, faster than 79.28%

* Time Complexity:O(N^2), whereNNis the number of events booked. For each new event, we process every previous event to decide whether the new event can be booked. This leads to ∑kN​ O(k) = O(N^2) complexity.
* Space Complexity: O(N), the size of the`calendar`.

```java
public class MyCalendarTwo {
    List<int[]> calendar;
    List<int[]> overlaps;

    MyCalendarTwo() {
        calendar = new ArrayList();
    }

    public boolean book(int start, int end) {
        for (int[] iv: overlaps) {
            if (iv[0] < end && start < iv[1]) return false;
        }
        for (int[] iv: calendar) {
            if (iv[0] < end && start < iv[1])
                overlaps.add(new int[]{Math.max(start, iv[0]), Math.min(end, iv[1])});
        }
        calendar.add(new int[]{start, end});
        return true;
    }
}
```

### Approach #2: Boundary Count: Use TreeMap + Loop

TreeMap用来排序所有的起始、终止节点，方便扫描线。ongoing变量记录当前的重叠的次数。

TreeMap相比于单纯用List存节点再排序的方法，更方便每次的增量更新，而List则需要每次全部排列之后再扫描，book()的时间复杂度是O(nlogn + n), worst case O(nlogn + nlogn)。

用TreeMap则book()只需要O(logn + n)时间，worst case每次不能插入新booking，或者说每次都有ongoing >= 3的情形要更新，则O(logn + n\*logn)。

* Time Complexity: 对于N次Booking来说，平均时间复杂度则为O(n(logn + n)) \~ O(n^2 + nlogn)
* Space Complexity: O(N)

191 ms, faster than 57.15%

```java
class MyCalendarTwo {
    TreeMap<Integer, Integer> calendar;

    public MyCalendarTwo() {
        calendar = new TreeMap<>();    
    }

    public boolean book(int start, int end) {
        calendar.put(start, calendar.getOrDefault(start, 0) + 1);
        calendar.put(end, calendar.getOrDefault(end, 0) - 1);

        int ongoing = 0;
        for (int v: calendar.values()) {
            ongoing += v;
            if (ongoing >= 3) {
                calendar.put(start, calendar.get(start) - 1);
                calendar.put(end, calendar.get(end) + 1);

                // --- optional to remove the tentative key --->
                if (calendar.get(start) == 0) {
                    calendar.remove(start);
                }
                if (calendar.get(end) == 0) {
                    calendar.remove(end);
                }
                // <--- optional to remove the tentative key ---

                return false;
            }
        }
        return true;
    }
}

/**
 * Your MyCalendarTwo object will be instantiated and called as such:
 * MyCalendarTwo obj = new MyCalendarTwo();
 * boolean param_1 = obj.book(start,end);
 */
```

## Reference

<https://leetcode.com/problems/my-calendar-ii/solution/>


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://aaronice.gitbook.io/lintcode/sweep-line/my-calendar-ii.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
