Algo-Sim › Intervals
My Calendar I
Medium · Intervals · step through it in Java, Python and C++ on your own input
Accept a booking [start, end) only if it overlaps nothing: in a sorted map, check just the floor and ceiling neighbours of start.
Problem
Implement MyCalendar with book(start, end), which adds the event [start, end) and returns true if it does not overlap any booked event. Otherwise return false and do not add it. Events [a, b) and [c, d) overlap when a < d and c < b.
Constraints
- 0 ≤ start < end ≤ 10⁹
- At most 1000 calls to book
Edge cases to test
- A booking that ends exactly when another starts is fine
- A booking inside an existing one
- The very first booking
Follow-up questions
- What if double bookings are allowed but not triple?
- Keep the double-booked overlaps in a second list and reject a booking that overlaps any of them (LC 731): O(n) per booking.
- What if you need the maximum overlap so far?
- A sorted map of +1/−1 at each boundary and a sweep (LC 732), or a segment tree with lazy propagation for O(log range).
Solution
Java
class MyCalendar {
private final TreeMap<Integer, Integer> booked = new TreeMap<>(); // start → end
public boolean book(int start, int end) {
// The booking just before must end by start; the one just after must start at or after end.
Integer prev = booked.floorKey(start);
Integer next = booked.ceilingKey(start);
if ((prev != null && booked.get(prev) > start) || (next != null && next < end))
return false;
booked.put(start, end);
return true;
}
}Python
from bisect import bisect_left, bisect_right
class MyCalendar:
def __init__(self):
# Parallel sorted lists (a SortedList would make inserts O(log n)).
self.starts, self.ends = [], []
def book(self, start, end):
# The booking just before must end by start; the one just after must start at or after end.
i = bisect_right(self.starts, start) - 1
j = bisect_left(self.starts, start)
if (i >= 0 and self.ends[i] > start) or (j < len(self.starts) and self.starts[j] < end):
return False
self.starts.insert(j, start)
self.ends.insert(j, end)
return TrueC++
#include <bits/stdc++.h>
using namespace std;
class MyCalendar {
map<int, int> booked; // start -> end
public:
bool book(int start, int end) {
// The booking just before must end by start; the one just after must start at or after end.
auto after = booked.upper_bound(start);
auto prev = after == booked.begin() ? booked.end() : std::prev(after);
auto next = booked.lower_bound(start);
if ((prev != booked.end() && prev->second > start) || (next != booked.end() && next->first < end))
return false;
booked[start] = end;
return true;
}
};
More Intervals problems
- Merge Intervals (Medium)
- Insert Interval (Medium)
- Non-overlapping Intervals (Medium)
- Meeting Rooms (Easy)
- Meeting Rooms II (Medium)
- Car Pooling (Difference Array) (Medium)
- Minimum Interval to Include Each Query (Hard)