A k-booking happens when k events have some non-empty intersection (i.e., there is some time that is common to all k events.)

You are given some events [startTime, endTime), after each given event, return an integer k representing the maximum k-booking between all the previous events.

Implement the MyCalendarThree class:

  • MyCalendarThree() Initializes the object.
  • int book(int startTime, int endTime) Returns an integer k representing the largest integer such that there exists a k-booking in the calendar.

Input & Output

Example 1 — Basic Booking Sequence
$ Input: operations = ["MyCalendarThree","book","book","book"], values = [[],[10,20],[15,25],[20,30]]
Output: [1,2,2]
💡 Note: First book(10,20) returns 1. Second book(15,25) overlaps with first, max k-booking is 2. Third book(20,30) doesn't increase maximum overlap, still 2.
Example 2 — Multiple Overlaps
$ Input: operations = ["MyCalendarThree","book","book","book","book"], values = [[],[10,40],[20,30],[25,35],[5,15]]
Output: [1,2,3,3]
💡 Note: Progressive overlap: first booking alone (1), second overlaps with first (2), third overlaps with both first and second at time 25-30 (3), fourth doesn't increase maximum.

Constraints

  • 0 ≤ start < end ≤ 109
  • At most 400 calls will be made to book

Visualization

Tap to expand
My Calendar III - Difference Array Approach INPUT Operations: ["MyCalendarThree","book", "book","book"] Event Intervals: 10 15 20 25 [10,20) [15,25) [20,30) Overlap Zone Values: [[],[10,20],[15,25],[20,30]] ALGORITHM STEPS 1 Use Sorted Map Track changes at each time 2 Mark Boundaries +1 at start, -1 at end 3 Sweep Line Sum changes in order 4 Track Maximum Return max k-booking Difference Map State: After book(10,20): {10:+1, 20:-1} After book(15,25): {10:+1, 15:+1, 20:-1, 25:-1} After book(20,30): {10:+1, 15:+1, 20:0, 25:-1, 30:-1} Sweep: 1 --> 2 --> 2 --> 1 --> 0 FINAL RESULT K-booking after each call: MyCalendarThree() Return: null book(10, 20) 1 k = 1 book(15, 25) 2 k = 2 book(20, 30) 2 k = 2 Output: [null, 1, 2, 2] OK - Maximum overlap = 2 Key Insight: The Difference Array technique marks +1 at event start and -1 at event end. By sweeping through the sorted map and accumulating values, we find the running count of overlapping events. The maximum accumulated value gives us the k-booking. Time: O(N^2), Space: O(N). TutorialsPoint - My Calendar III | Difference Array with Map Approach
Asked in
Google 25 Amazon 18 Microsoft 15
28.0K Views
Medium Frequency
~25 min Avg. Time
856 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