My Calendar II

Medium Topics Company Tags

Implement MyCalendarTwo, a calendar that allows two simultaneous events but never three.

  • MyCalendarTwo() creates an empty calendar.
  • book(startTime, endTime) tries to add the half-open interval [startTime, endTime). Return true and store it if no time would belong to three events. Otherwise, return false and leave the calendar unchanged.

An event includes its start time and excludes its end time. Events that only touch at an endpoint do not overlap.

Example 1:

Input: ["MyCalendarTwo","book","book","book","book"]
[[],[2,8],[4,10],[6,7],[8,12]]

Output: [null,true,true,false,true]

Explanation: The first two bookings overlap during [4,8), which is allowed. [6,7) would create three simultaneous events and is rejected. [8,12) is accepted because the first booking ends at 8.

Example 2:

Input: ["MyCalendarTwo","book","book","book"]
[[],[0,5],[5,10],[0,10]]

Output: [null,true,true,true]

Explanation: The first two events only touch at time 5. Adding [0,10) creates two simultaneous events throughout, never three, so all bookings succeed.

Example 3:

Input: ["MyCalendarTwo","book","book","book","book"]
[[],[1,4],[1,4],[1,4],[4,6]]

Output: [null,true,true,false,true]

Explanation: Two identical bookings are allowed. The third identical booking is rejected, and the calendar keeps only the first two. The final event begins exactly when those events end, so it is accepted.

Constraints:

  • 0 <= startTime < endTime <= 1000000000
  • At most 1000 calls are made to book.


Topics

Company Tags

Please upgrade to NeetCode Pro to view company tags.