Leetcode 731: My Calendar II

grid47
grid47
Exploring patterns and algorithms
Aug 25, 2024 6 min read

A calendar with overlapping events, where conflicts are highlighted and softly glowing to indicate double-booking.
Solution to LeetCode 731: My Calendar II Problem

You are implementing a calendar system where you can add events. Each event is represented by a start time and an end time, defined as a half-open interval [startTime, endTime). You need to ensure that no more than two events overlap at any given time, or else return false. Your task is to implement a class, MyCalendarTwo, that will book events while preventing triple bookings.
Problem
Approach
Steps
Complexity
Input: The input consists of an array of method calls with parameters. The first call is always the initialization of the MyCalendarTwo object, followed by calls to the book method.
Example: Input: ["MyCalendarTwo", "book", "book", "book", "book", "book", "book"] [[], [10, 20], [50, 60], [10, 40], [5, 15], [5, 10], [25, 55]]
Constraints:
• 0 <= start < end <= 10^9
• At most 1000 calls will be made to book.
Output: The output will be an array of boolean values for each call. The first call to the MyCalendarTwo constructor returns null. For each book method call, return true if the event can be booked without causing a triple booking, and false otherwise.
Example: Output: [null, true, true, true, false, true, true]
Constraints:
• The response for each book method call is a boolean indicating whether the event was successfully booked or not.
Goal: The goal is to design a method that tracks the number of overlapping events at any time and ensures that no more than two events overlap.
Steps:
• 1. Use a data structure to track the number of events occurring at any given time.
• 2. For each new booking, update the event count at the corresponding start and end times.
• 3. Check if the number of overlapping events exceeds 2 at any point.
• 4. If more than two events overlap, revert the booking and return false. Otherwise, return true.
Goal: The constraints define the input limits and behavior of the system.
Steps:
• 0 <= start < end <= 10^9
• At most 1000 calls will be made to book.
Assumptions:
• The start and end times of events are valid integers, and events are well-formed.
Input: Input: ["MyCalendarTwo", "book", "book", "book", "book", "book", "book"] [[], [10, 20], [50, 60], [10, 40], [5, 15], [5, 10], [25, 55]]
Explanation: In this example, the first three events are successfully booked as they do not overlap more than twice. The fourth event fails as it causes a triple booking. The fifth event is booked because it only overlaps with one event at any time.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus