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.

Input & Output

Example 1 — Basic Calendar Operations
$ Input: operations = ["MyCalendarTwo", "book", "book", "book"], parameters = [[], [10,20], [50,60], [10,40]]
Output: [null, true, true, false]
💡 Note: First booking [10,20) succeeds. Second booking [50,60) succeeds (no overlap). Third booking [10,40) would overlap with [10,20) creating double booking, but since it would also create triple overlap at time 10-20, it's rejected.
Example 2 — Double Booking Allowed
$ Input: operations = ["MyCalendarTwo", "book", "book", "book", "book"], parameters = [[], [10,20], [15,25], [20,30], [5,15]]
Output: [null, true, true, true, false]
💡 Note: First three bookings create overlapping regions but no triple booking. Fourth booking [5,15] would create triple overlap in range [10,15], so it's rejected.
Example 3 — Edge Case with Same Times
$ Input: operations = ["MyCalendarTwo", "book", "book"], parameters = [[], [1,2], [2,3]]
Output: [null, true, true]
💡 Note: Intervals [1,2) and [2,3) don't overlap since the first ends exactly when the second starts (half-open intervals).

Constraints

  • 0 ≤ startTime < endTime ≤ 109
  • At most 1000 calls will be made to book

Visualization

Tap to expand
My Calendar II: Double Booking AllowedOperations: book(10,20), book(50,60), book(10,40)[10, 20) ✓[50, 60) ✓[10, 40) ✗Third booking would overlap with first: [10,20) creating double bookingBut this extends to [40) which could allow future triple bookingsOutput: [null, true, true, false]✓ Double booking OK | ✗ Triple booking rejected
Understanding the Visualization
1
Input
Series of booking operations with time intervals
2
Process
Check if adding booking would create triple overlap
3
Output
Boolean array indicating success/failure of each booking
Key Takeaway
🎯 Key Insight: Track overlap regions separately - if new booking overlaps with existing double booking, it creates triple booking
Asked in
Google 45 Amazon 38 Microsoft 32 Facebook 28
67.0K Views
Medium Frequency
~25 min Avg. Time
1.9K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen