#732

My Calendar III

Hard
Binary SearchDesignSegment TreePrefix SumOrdered SetSweep LineSortingEvent Counting
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n log n)
Space
O(1)
O(n)
💡

Intuition

Time O(n log n)Space O(n)

The optimal solution uses a sweep line algorithm where we treat each booking as two events: a start and an end. By sorting these events and counting overlaps, we can efficiently determine the maximum number of overlapping bookings.

⚙️

Algorithm

3 steps
  1. 1Step 1: Create an array of events, where each booking contributes a start and an end event.
  2. 2Step 2: Sort the events first by time, and then by type (start before end if they are the same time).
  3. 3Step 3: Traverse the sorted events, maintaining a count of active bookings and updating the maximum count.
solution.py14 lines
1class MyCalendarThree:
2    def __init__(self):
3        self.events = []
4
5    def book(self, startTime: int, endTime: int) -> int:
6        self.events.append((startTime, 1))  # Start event
7        self.events.append((endTime, -1))    # End event
8        self.events.sort()  # Sort events
9        max_k = 0
10        current_k = 0
11        for time, count in self.events:
12            current_k += count
13            max_k = max(max_k, current_k)
14        return max_k

Complexity note: The time complexity is dominated by the sort operation, which is O(n log n). The space complexity is O(n) due to storing the events.

  • 1Each booking can be represented as two events: a start and an end.
  • 2Sorting events allows us to efficiently count overlaps in a single pass.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.