Implement book(start, end) for half-open intervals [start, end). Add the booking and return true if it doesn't overlap any existing booking; otherwise return false and leave the calendar unchanged.
Before you code
Existing bookings never overlap each other, so sorted by start they are also sorted by end. Which two existing bookings can possibly conflict with a new one?
Hints
- Keep bookings in an ordered map from start to end: TreeMap in Java, std::map in C++, SortedDict or a sorted list with bisect in Python.
- The new booking fits when the previous booking ends at or before start, and the next booking starts at or after end.
- Each book is one floor and one ceiling query: O(log n) with a balanced tree.
Production & complexity notes
When solving My calendar I on LeetCode (medium), always state your loop or recursion invariant before writing code. Verify how your chosen data structure behaves on degenerate inputs (single-element inputs, all-duplicate keys, strictly monotonic sequences, or maximum constraint sizes up to $10^5$ elements). In production interviews, pair your implementation with an explicit time and auxiliary space complexity proof, explain why alternative brute-force approaches violate the latency budget, and trace how cache locality and memory allocation overhead affect wall-clock throughput on real hardware. Review the step-by-step memory trace in Red-black trees to reinforce the underlying pattern.
What it practices
Floor and ceiling queries on an ordered map, from Red-black trees.