My Calendar II
01 · Problem
Your calendar now tolerates some overlap: two events may share time, but three may not. Each event is the half-open range [start, end), covering every t with start <= t < end. A triple booking happens when some moment is covered by three events at once. Events that only touch at an endpoint do not overlap.
Implement the MyCalendarTwo class:
MyCalendarTwo()creates an empty calendar.boolean book(int start, int end)tries to add the event[start, end). If adding it would not create a triple booking, store it and returntrue. Otherwise leave the calendar unchanged and returnfalse.
Rejected events are never stored.
The input lists the operation names and their argument lists. The output lists each call's return value, using null for the constructor.
02 · Examples
["MyCalendarTwo","book","book","book","book","book","book"], [[],[10,20],[50,60],[10,40],[5,15],[5,10],[25,55]]
[null,true,true,true,false,true,true]
[10,40) double-books [10,20). [5,15) would cover [10,15) a third time, so it is rejected. [5,10) only touches [10,20) and [10,40) at 10, so it is accepted. [25,55) double-books [25,40) and [50,55) but never triples.
["MyCalendarTwo","book","book","book","book"], [[],[1,5],[2,6],[3,4],[5,7]]
[null,true,true,false,true]
[1,5) and [2,6) overlap on [2,5). [3,4) falls inside that double-booked region, so it is rejected. [5,7) overlaps only [2,6), on [5,6).
["MyCalendarTwo","book","book","book","book"], [[],[0,10],[0,10],[0,10],[10,20]]
[null,true,true,false,true]
The same slot can be booked twice but not a third time. [10,20) only touches the existing events.
03 · Constraints
- 010 <= start < end <= 109
- 02At most 1000 calls will be made to book
- 03Event ranges are half-open: [start, end)
04 · Optimal complexity
- Time
- O(n) per book
- Space
- O(n)
Practice it alone or rehearse it as an interview.
Practice Mode gives you an editor and test runs, nothing else. AI Interview Mode puts a voice interviewer on the other side, adds a clock, and ends with a scored summary of the round.