Process Calendar Events with Deletion, Pagination, and Overlap Queries
Lead BankSoftware Engineer · OnsiteLast updated
This problem tests your ability to manage a dynamic set of time-interval events using a data structure that allows for logarithmic insertions, deletions, and efficient range-based queries.
Problem Statement
You are tasked with building an in-memory calendar system that tracks events defined by a start time and an end time. Each event is stored as a half-open interval [start, end).
Implement the Calendar class with the following methods:
add_event(event_id: str, start: int, end: int): Adds an event. If an event with the same ID already exists, update its interval.delete_event(event_id: str): Removes the event with the given ID. If the ID does not exist, do nothing.get_overlaps(start: int, end: int): Returns a list of allevent_ids that overlap with the provided[start, end)range. An overlap occurs ifmax(start, event_start) < min(end, event_end).get_page(page_number: int, page_size: int): Returns a list of event IDs for the specified page. Events must be ordered primarily bystarttime (ascending), and secondarily byevent_id(alphabetical) for stability.
Constraints
startandendare integers in the range[0, 10^9].page_numberis 0-indexed.- Total number of events
Ncan reach10^5.
Examples
# Example 1
cal = Calendar()
cal.add_event("A", 10, 20)
cal.add_event("B", 15, 25)
cal.get_overlaps(12, 18) # Returns ["A", "B"]
cal.delete_event("A")
cal.get_overlaps(12, 18) # Returns ["B"]
Edge Cases
- Zero-length intervals or inverted intervals.
- Large number of events resulting in many pages.
- Overlaps exactly on the boundaries (note: the interval is half-open).
Hints
Hint 1
Use a dictionary to map `event_id` to its interval for O(1) deletions and lookups.
Hint 2
For overlap queries, a Segment Tree or an Interval Tree can efficiently handle range searching in O(log N + K) time.
Hint 3
For pagination, maintain a sorted structure (like a SortedList or a balanced BST) that stores tuples of `(start, event_id)` to allow for efficient slicing.
Follow-up questions
- How would your architecture change if the calendar needed to support recurring events (e.g., repeating every Monday)?
- If the calendar is heavily read-optimized with infrequent writes, how could you pre-calculate the pagination pages?
- How would you handle thread safety if multiple users add and delete events simultaneously?
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.