Interactive Time Calendar with Pagination and Range Queries
Data Structure DesignAuto-graded · 18 test casesLast updated
Process dynamic interval updates, range queries, and ordered pagination operations efficiently.
Design an in-memory calendar tracking system that manages time intervals defined as half-open ranges [start, end).
Implement the function process_calendar_operations(operations, arguments) which processes a sequential list of command strings and their corresponding argument lists, returning a list containing the result of each operation.
The supported operations and their behaviors are:
-
add_event(event_id: str, start: int, end: int)- Adds or updates an event identified by
event_idwith time bounds[start, end). - If
event_idis already stored, its interval is modified to[start, end). - Returns
None. - Note: Events can be added with
start >= end(e.g., zero-length or invalid intervals). These events are included in pagination but never match any overlap query.
- Adds or updates an event identified by
-
delete_event(event_id: str)- Deletes the event associated with
event_id. Ifevent_iddoes not exist, does nothing. - Returns
None.
- Deletes the event associated with
-
get_overlaps(start: int, end: int)- Retrieves all active events whose interval
[e_start, e_end)overlaps with the query interval[start, end). - Two half-open intervals overlap if
max(start, e_start) < min(end, e_end)ande_start < e_end. - Returns a list of matching
event_idstrings sorted primarily bye_startascending, and secondarily byevent_idin standard lexicographical order. - If
start >= end, returns an empty list[].
- Retrieves all active events whose interval
-
get_page(page_number: int, page_size: int)- Returns a list of
event_idstrings corresponding to the requested page. - All currently active events are sorted primarily by
start(ascending) and secondarily byevent_id(lexicographically). - Pages are 0-indexed. Page $p$ of size $s$ includes events at 0-based indices from $p \times s$ up to $\min((p + 1) \times s, N)$, where $N$ is the total count of active events.
- Returns
[]ifpage_number < 0,page_size <= 0, orpage_number * page_size >= N.
- Returns a list of
Constraints
- $0 \le start, end \le 10^9$
- Total number of operations across all calls $\le 10^5$
event_idis a non-empty string.
Format
- The function receives
operationsasList[str]andargumentsasList[List[Any]]. - The returned list has length equal to
len(operations), where each entry isNone(foradd_event/delete_event) or a list ofstr(forget_overlaps/get_page).
Examples
Example 1
Input: process_calendar_operations(['add_event', 'add_event', 'get_overlaps', 'delete_event', 'get_overlaps'], [['A', 10, 20], ['B', 15, 25], [12, 18], ['A'], [12, 18]])
Output: [None, None, ['A', 'B'], None, ['B']]
Example 2
Input: process_calendar_operations(['add_event', 'add_event', 'add_event', 'get_page', 'get_page'], [['B', 20, 30], ['A', 10, 20], ['C', 10, 15], [0, 2], [1, 2]])
Output: [None, None, None, ['A', 'C'], ['B']]
Example 3
Input: process_calendar_operations(['add_event', 'add_event', 'get_overlaps', 'get_overlaps'], [['A', 0, 10], ['B', 10, 20], [0, 10], [10, 20]])
Output: [None, None, ['A'], ['B']]
Hints
Hint 1
Use a dictionary mapping event_id to (start, end) for O(1) attribute lookups during updates and deletions.
Hint 2
Store events in an augmented self-balancing binary search tree (like a Treap) keyed by (start, event_id).
Hint 3
Augment tree nodes with subtree size (for logarithmic k-th element pagination) and max_end (to prune non-overlapping subtrees).
Worked solution
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Approach
To efficiently process dynamic insertions, deletions, interval queries, and order-based pagination, we combine a Hash Map with an Augmented Treap (Randomized Binary Search Tree):
- BST Key Structure: Every node is keyed by
(start, event_id). Becauseevent_idis unique, this composite key forms a strict total order. In-order traversal of the tree directly matches the ordering required for both pagination and overlap reporting. - Auxiliary Hash Map: An
eventshash map storesevent_id -> (start, end). When an existing event is updated or removed, its old key(old_start, event_id)can be constructed in $O(1)$ time to erase the node from the Treap in $O(\log N)$ time. - Subtree Size Augmentation (
size): Each node keeps track of the size of its subtree. This allows finding the $k$-th element in $O(\log N)$ time, makingget_pageoperations straightforward. - Subtree Max End Augmentation (
max_end): Each node storesmax_end, the maximum interval end point in its entire subtree. For an overlap query[qs, qe):- If a subtree's
max_end <= qs, no interval in that subtree extends far enough to overlap with the query range, so the subtree is pruned. - If a node's
start >= qe, no node in its right subtree can overlap because all right-subtree nodes havestart >= qe.
- If a subtree's
Complexity
- Add Event / Delete Event: $O(\log N)$ expected time per call.
- Get Page: $O(P \log N)$ expected time where $P$ is the page size.
- Get Overlaps: $O((K + 1) \log N)$ expected time where $K$ is the number of overlapping events returned.
- Space Complexity: $O(N)$ space to maintain $N$ active events in memory.
Python Reference Solution
import random
from typing import List, Any
class _Node:
__slots__ = ("key", "event_id", "start", "end", "priority", "left", "right", "size", "max_end")
def __init__(self, key, event_id, start, end, priority):
self.key = key
self.event_id = event_id
self.start = start
self.end = end
self.priority = priority
self.left = None
self.right = None
self.size = 1
self.max_end = end
def _size(node):
return node.size if node else 0
def _max_end(node):
return node.max_end if node else -1
def _update(node):
if node:
node.size = 1 + _size(node.left) + _size(node.right)
node.max_end = max(node.end, _max_end(node.left), _max_end(node.right))
return node
def _split(root, key):
if root is None:
return None, None
if root.key < key:
a, b = _split(root.right, key)
root.right = a
return _update(root), b
a, b = _split(root.left, key)
root.left = b
return a, _update(root)
def _merge(a, b):
if a is None:
return b
if b is None:
return a
if a.priority < b.priority:
a.right = _merge(a.right, b)
return _update(a)
b.left = _merge(a, b.left)
return _update(b)
def _insert(root, node):
if root is None:
return node
if node.priority < root.priority:
node.left, node.right = _split(root, node.key)
return _update(node)
if node.key < root.key:
root.left = _insert(root.left, node)
else:
root.right = _insert(root.right, node)
return _update(root)
def _erase(root, key):
if root is None:
return None
if key == root.key:
return _merge(root.left, root.right)
if key < root.key:
root.left = _erase(root.left, key)
else:
root.right = _erase(root.right, key)
return _update(root)
def _kth(root, index):
while root is not None:
left_size = _size(root.left)
if index < left_size:
root = root.left
elif index == left_size:
return root
else:
index -= left_size + 1
root = root.right
return None
def _collect_overlaps(root, query_start, query_end, result):
if root is None or root.max_end <= query_start:
return
if root.left is not None and root.left.max_end > query_start:
_collect_overlaps(root.left, query_start, query_end, result)
if root.start < query_end and root.end > query_start and root.start < root.end:
result.append(root.event_id)
if root.start < query_end:
_collect_overlaps(root.right, query_start, query_end, result)
def process_calendar_operations(operations: List[str], arguments: List[List[Any]]) -> List[Any]:
rng = random.Random(917263)
root = None
events = {}
output = []
for operation, args in zip(operations, arguments):
if operation == "add_event":
event_id, start, end = args
if event_id in events:
old = events[event_id]
root = _erase(root, (old[0], event_id))
node = _Node((start, event_id), event_id, start, end, rng.random())
root = _insert(root, node)
events[event_id] = (start, end)
output.append(None)
elif operation == "delete_event":
event_id = args[0]
old = events.pop(event_id, None)
if old is not None:
root = _erase(root, (old[0], event_id))
output.append(None)
elif operation == "get_overlaps":
start, end = args
result = []
if start < end:
_collect_overlaps(root, start, end, result)
output.append(result)
elif operation == "get_page":
page_number, page_size = args
if page_number < 0 or page_size <= 0:
output.append([])
continue
first = page_number * page_size
total = _size(root)
if first >= total:
output.append([])
continue
last = min(first + page_size, total)
page = []
for index in range(first, last):
page.append(_kth(root, index).event_id)
output.append(page)
else:
raise ValueError("unknown operation")
return output