Problem
LeetCode #729 — one-liner.
- Implement
book(start, end)that returnstrueif the new half-open event can be added without overlapping any existing booking, otherwisefalse.
Key insight
Half-open overlap check.
- Overlap formula:
start < existing_end AND end > existing_start(strict<,>because[start, end)is half-open). - Linear scan over existing bookings per call. BST / SortedList optimisation brings per-call to
O(log n).
Solution template
Seven lines.
class MyCalendar:
def __init__(self): self.bookings = []
def book(self, start, end):
for s, e in self.bookings:
if start < e and end > s:
return False
self.bookings.append((start, end))
return TrueComplexity
Per-call cost.
- Time per
bookO(n)with a list;O(log n)with a balanced BST / SortedList. - Space
O(n)— stores all accepted bookings.
Edge cases
One to remember.
- Adjacent half-open events
[10, 20)+[20, 30)— no overlap (20 < 20is false). That’s the point of half-open semantics.
Comments
Comments are disabled in this environment. Set
PUBLIC_GISCUS_REPO,PUBLIC_GISCUS_REPO_ID, andPUBLIC_GISCUS_CATEGORY_IDto enable.