Search lands in PR-5.1 (Pagefind).

How-to Intermediate

Chapter 1 Updated

My Calendar I

Overlap test per booking: start < existing_end AND end > existing_start.

  • Full 5m
  • Revision 2m
  • Flow 1m

Problem Statement

Design a calendar class with a single method book(start, end). A new event can be added only if it doesn’t cause a double booking — i.e. doesn’t overlap any previously booked event. Events are half-open intervals [start, end).

Input

Sequential calls to book(start, end), each proposing a new event.

Example call sequence
book(10, 20)
book(15, 25)
book(20, 30)

Output

Each book call returns true if the booking was added, false if rejected because it would overlap an existing one.

Expected returns
true     # [10,20) — first event, added
false    # [15,25) — overlaps [10,20), rejected
true     # [20,30) — touches [10,20) at 20 (half-open), added

Constraints

  • 0 ≤ start < end ≤ 10⁹
  • At most 1000 calls to book.

Intuition

For each new booking, scan the existing ones and test for overlap using the universal half-open formula:

Overlap test (half-open)
   start < existing_end   AND   end > existing_start

If any existing booking overlaps → reject. Otherwise, store the booking and return true.

Solution

my_calendar_i.py
class MyCalendar:
    def __init__(self):
        self.bookings = []
 
    def book(self, start: int, end: int) -> bool:
        for s, e in self.bookings:
            if start < e and end > s:  # overlap check
                return False
        self.bookings.append((start, end))
        return True
 
# book() → O(n) per call.  Optimized: SortedList → O(log n)

Complexity

MetricValueReason
Time (per call)O(n)Scans all existing bookings
SpaceO(n)Stores every accepted booking

Edge Case Thinking

ScenarioHandling
Adjacent events [10,20) & [20,30)No overlap! 20 < 20 is false. Half-open intervals prevent false conflicts on boundaries.
Book identical event twiceSecond call rejected — strict overlap (start < e AND end > s) holds for identical intervals.
First call with no existing bookingsLoop doesn’t execute → event is accepted.
Optimisation pathSwap the list for a balanced BST (Python’s SortedList) and binary-search the insertion point → O(log n) per call.

Comments

Comments are disabled in this environment. Set PUBLIC_GISCUS_REPO, PUBLIC_GISCUS_REPO_ID, and PUBLIC_GISCUS_CATEGORY_ID to enable.