729. My Calendar I #613
-
Topics: 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 Implement the
Example 1:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We need to store each event and check if the new event conflicts with any of the existing events before booking it. Since at most 1000 calls to Plan:
Let's implement this solution in PHP: 729. My Calendar I <?php
class MyCalendar {
/**
* @var array
*/
private $events;
/**
*/
function __construct() {
// Initialize an empty array to store the booked events
$this->events = [];
}
/**
* Books an event if it does not cause a double booking
*
* @param Integer $start
* @param Integer $end
* @return Boolean
*/
function book($start, $end) {
// Check for any conflicts with existing events
foreach ($this->events as $event) {
$bookedStart = $event[0];
$bookedEnd = $event[1];
// Overlap occurs if the new event's start is before the end of the current event
// and the new event's end is after the start of the current event
if ($start < $bookedEnd && $end > $bookedStart) {
return false; // Conflict found, booking not possible
}
}
// No conflicts found, add the new event
$this->events[] = [$start, $end];
return true;
}
}
/**
* Your MyCalendar object will be instantiated and called as such:
* $obj = MyCalendar();
* $ret_1 = $obj->book($start, $end);
*/
// Example Usage:
$myCalendar = new MyCalendar();
var_dump($myCalendar->book(10, 20)); // true, no conflicts, booking added
var_dump($myCalendar->book(15, 25)); // false, conflict with [10, 20]
var_dump($myCalendar->book(20, 30)); // true, no conflicts, booking added
?> Explanation:
Time Complexity:
Example Walkthrough:
This simple approach efficiently handles up to 1000 events while maintaining clarity and correctness. |
Beta Was this translation helpful? Give feedback.
We need to store each event and check if the new event conflicts with any of the existing events before booking it. Since at most 1000 calls to
book
are allowed, we can store the events in a list and iterate through them to check for overlaps when booking new events.Plan:
[start, end]
representing the booked time intervals.