My Calendar I - 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 double booking.
A double booking happens when two events have some non-empty intersection (i.e., some moment is common to both 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 MyCalendar class:
MyCalendar()Initializes the calendar object.boolean book(int startTime, int endTime)Returnstrueif the event can be added to the calendar successfully without causing a double booking. Otherwise, returnfalseand do not add the event to the calendar.
Input & Output
Example 1 — Basic Calendar Operations
$
Input:
commands = ["MyCalendar", "book", "book", "book"], parameters = [[], [10, 20], [15, 25], [20, 30]]
›
Output:
[null, true, false, true]
💡 Note:
MyCalendar() initializes calendar. book(10,20) returns true (first booking). book(15,25) returns false (overlaps with [10,20)). book(20,30) returns true (no overlap since [10,20) ends at 20).
Example 2 — Adjacent Bookings
$
Input:
commands = ["MyCalendar", "book", "book"], parameters = [[], [10, 20], [20, 30]]
›
Output:
[null, true, true]
💡 Note:
book(10,20) succeeds. book(20,30) succeeds because intervals [10,20) and [20,30) don't overlap (20 is not included in first interval).
Example 3 — Multiple Overlaps
$
Input:
commands = ["MyCalendar", "book", "book", "book", "book"], parameters = [[], [5, 10], [25, 30], [15, 20], [12, 18]]
›
Output:
[null, true, true, true, false]
💡 Note:
First three bookings succeed. book(12,18) fails because it overlaps with [15,20): max(12,15) < min(18,20) → 15 < 18 is true.
Constraints
- 0 ≤ start < end ≤ 109
- At most 1000 calls will be made to book
Visualization
Tap to expand
Understanding the Visualization
1
Input
Booking requests with start and end times
2
Process
Check for overlaps with existing bookings
3
Output
Return true/false for each booking attempt
Key Takeaway
🎯 Key Insight: Two intervals overlap if their intersection is non-empty - use max(start1,start2) < min(end1,end2) to detect overlaps efficiently
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code