Dynamic Interval Calendar with Overlap and Page Queries
Medium · Coding & Algorithms · Software Engineer · Onsite
Problem Statement
Implement process_calendar_operations(operations: List[str], arguments: List[List]) -> List to maintain a dynamic collection of scheduled events and return the output produced by each command in operations.
Every event has a unique string identifier event_id and occupies a half-open integer time interval [start, end) (start included, end excluded). For each index i, execute operations[i] with arguments[i]:
"add_event"with[event_id, start, end]: Inserts(event_id, start, end)into the calendar, or replaces its interval ifevent_idis already present. AppendsNoneto the returned list."delete_event"with[event_id]: Removesevent_idif it exists; does nothing ifevent_idis absent. AppendsNoneto the returned list."get_overlaps"with[start, end]: Returns all activeevent_ids whose interval[event_start, event_end)overlaps[start, end)according tomax(start, event_start) < min(end, event_end), ordered by ascendingevent_startand then alphabetically (<) byevent_id."get_page"with[page_number, page_size]: Orders all currently active events by ascendingstarttime and breaks ties alphabetically (<) byevent_id, returning theevent_ids on0-indexed pagepage_numberof sizepage_size(or[]whenpage_number < 0,page_size <= 0, or the page starts past the active events).
Note that zero-length or inverted events (event_start >= event_end) remain active in the schedule for "get_page", whereas max(start, event_start) < min(end, event_end) is always false whenever either the event or query has start >= end.
def process_calendar_operations(operations: List[str], arguments: List[List]) -> List:
...
Examples
Example 1
Input:
operations = ["add_event", "add_event", "add_event", "get_overlaps", "delete_event", "get_overlaps"]
arguments = [["sync", 30, 50], ["demo", 40, 65], ["retro", 50, 70], [35, 50], ["sync"], [35, 55]]
Output:
[None, None, None, ["sync", "demo"], None, ["demo", "retro"]]
On get_overlaps(35, 50), "sync" ([30, 50)) and "demo" ([40, 65)) overlap [35, 50), while "retro" ([50, 70)) only touches the right endpoint 50 and is excluded. After deleting "sync", get_overlaps(35, 55) matches "demo" and "retro".
Example 2
Input:
operations = ["add_event", "add_event", "add_event", "add_event", "get_page", "get_page"]
arguments = [["standup", 100, 115], ["plan", 80, 120], ["kickoff", 80, 95], ["standup", 75, 90], [0, 2], [1, 2]]
Output:
[None, None, None, None, ["standup", "kickoff"], ["plan"]]
Re-adding "standup" moves it from [100, 115) to [75, 90). Sorting active events by (start, event_id) yields (75, "standup"), (80, "kickoff"), (80, "plan"), so page 0 of size 2 is ["standup", "kickoff"] and page 1 is ["plan"].
Example 3
Input:
operations = ["add_event", "add_event", "get_overlaps", "get_overlaps", "get_page"]
arguments = [["slot_1", 5, 15], ["slot_2", 15, 25], [15, 20], [14, 16], [2, 2]]
Output:
[None, None, ["slot_2"], ["slot_1", "slot_2"], []]
Half-open [5, 15) does not intersect [15, 20) (max(15, 5) < min(20, 15) is 15 < 15, false), whereas [14, 16) straddles 15 and hits both events. Requesting 0-based page 2 of size 2 with only 2 active events returns [].
Constraints
- Up to
10^5total operations and up to10^5active events 0 <= start, end <= 10^9(zero-length or inverted intervals withstart >= endmay appear)page_numberis0-indexed; out-of-range pages return[]- Both
"get_page"and"get_overlaps"returnevent_ids ordered by(start, event_id)
Step-by-step walkthrough
Unpack the half-open overlap rule and page order
Our
Calendarmanages events with IDs and half-open intervals[start, end), driven byprocess_calendar_operations(operations, arguments):add_event(id, start, end)-> adds or updatesid(returnsNone).delete_event(id)-> removesidif present (returnsNone).get_overlaps(q_start, q_end)-> returns all overlappingevent_ids.get_page(page_number, page_size)-> returns the0-indexed page ofevent_ids sorted by(start, event_id).
Let's carefully unpack the exact overlap formula
max(q_start, e_start) < min(q_end, e_end). The larger of{q_start, e_start}is strictly smaller than the smaller of{q_end, e_end}if and only if both numbers on the left are strictly smaller than both numbers on the right:max(q_start, e_start) < min(q_end, e_end) <=> 1) q_start < q_end (query window has positive length) and 2) e_start < e_end (event itself has positive length) and 3) e_start < q_end (event starts strictly before query ends) and 4) e_end > q_start (event ends strictly after query starts) Touching half-open intervals do NOT overlap (Example 3): slot_1: [5, 15) slot_2: [15, 25) |-------| |-------| max(5, 15) = 15 is NOT < min(15, 25) = 15 --> no overlap!Notice two consequences right away: - Zero-length (
[5, 5)) and inverted ([20, 10)) events still exist in the calendar (so they appear inget_page), but condition #2 (e_start < e_end) means they never overlap any query. - Returningget_overlapsin the same(start, event_id)order asget_pagekeeps all outputs deterministic and matches Example 1 (["sync", "demo"]).Why sorting or scanning on every query is too slow
A simple reference implementation keeps
events = {event_id: (start, end)}and sorts or scanseventson each query.With up to
N = 10^5events and10^5operations: - Re-sorting on everyget_pagetakesO(N log N)per query (~10^10+ steps total). - Scanning every event on everyget_overlapstakesO(N)per query — even when a narrow query like[14, 16)only hits1or2events! - Keeping a plain sorted Pythonlistmakes page slicing fast, but inserting or deleting in the middle shifts up toNelements inO(N)time.We need a structure sorted by
(start, event_id)where insertions and deletions takeO(log N)time, pagination jumps straight to any rank, and overlap search skips whole blocks of non-overlapping events.Key idea: a segment tree over sorted `(start, event_id)` slots
Because
process_calendar_operationsgives us the entire list of operations up front, we can pre-scan alladd_eventcalls, collect every(start, event_id)pair that could ever exist, sort unique pairs once intoself.keys, and give each pair a fixed leaf index called a slot.Over those sorted slots we build a binary segment tree where each node summarizes its range of slots with two numbers: -
count[node]: how many active events currently sit in this subtree (used byget_pageto jump to thek-th event), -max_end[node]: the largestendamong active positive-length events in this subtree, or-infif none (used byget_overlapsto skip an entire subtree whenevermax_end[node] <= q_start).Here is what the tree looks like after all four
add_eventcalls in Example 2 (standupupdated from[100, 115)to[75, 90),kickoff: [80, 95),plan: [80, 120)):[node 1: slots 0..3] count=3, max_end=120 / \ [node 2: slots 0..1] [node 3: slots 2..3] count=2, max_end=95 count=1, max_end=120 / \ / \ slot 0 slot 1 slot 2 slot 3 (75,"standup"):90 (80,"kickoff"):95 (80,"plan"):120 (100,"standup") cnt=1,end=90 cnt=1,end=95 cnt=1,end=120 cnt=0,end=-infBuild the slot index and bottom-up update helper
We round the leaf capacity
self.sizeup to the next power of two so the tree fits cleanly in flat arrays of length2 * self.size: - Node1is the root. - Nodeihas left child2 * iand right child2 * i + 1. - Leafslotlives at array indexself.size + slot.Whenever a slot turns on (
active_count = 1) or off (active_count = 0),_update_slotwrites the leaf and walks upnode //= 2to recompute itsO(log M)ancestors.from typing import Dict, List, Tuple # Sentinel end time for empty tree slots and zero/inverted events so they never match a query. NO_OVERLAP_END = float("-inf") class Calendar: """In-memory calendar backed by a segment tree over sorted (start, event_id) slots.""" def __init__(self, candidate_keys: List[Tuple[int, str]]) -> None: # Phase 1: Coordinate-compress every (start, event_id) pair that may ever be added. # keys: sorted unique [(start, event_id), ...], e.g. [(75, "standup"), (80, "kickoff"), (80, "plan")] self.keys: List[Tuple[int, str]] = sorted(set(candidate_keys)) # slot_of: {(start, event_id): leaf_slot_index} for O(1) slot lookup on add/delete. self.slot_of: Dict[Tuple[int, str], int] = {} for slot_index, key in enumerate(self.keys): self.slot_of[key] = slot_index # Round leaf count up to a power of two so node 1 is the root and slot s lives at size + s. self.size = 1 while self.size < len(self.keys): self.size *= 2 # count[node]: number of active events inside node's slot range (for O(log M) pagination). # max_end[node]: largest end time among active valid events in node's range (for pruning). self.count: List[int] = [0] * (2 * self.size) self.max_end: List[float] = [NO_OVERLAP_END] * (2 * self.size) # events: {event_id: (start, end)} for O(1) lookup of an existing ID during delete/update. self.events: Dict[str, Tuple[int, int]] = {} def _update_slot(self, slot: int, active_count: int, effective_end: float) -> None: """Write leaf `slot` and recompute count and max_end up to the root in O(log M) time.""" node = self.size + slot self.count[node] = active_count self.max_end[node] = effective_end node //= 2 while node >= 1: left_child = 2 * node right_child = left_child + 1 self.count[node] = self.count[left_child] + self.count[right_child] self.max_end[node] = max(self.max_end[left_child], self.max_end[right_child]) node //= 2Implement `add_event` and `delete_event`
self.eventsmaps each activeevent_idto(start, end)sodelete_eventcan find its oldstartinO(1)time and switch off(old_start, event_id).Calling
self.delete_event(event_id)at the start ofadd_eventhandles updates cleanly: in Example 2, when"standup"moves from[100, 115)to[75, 90), its old slot(100, "standup")is cleared before its new slot(75, "standup")is switched on. For zero-length or inverted events (start >= end), we setactive_count = 1(soget_pagestill counts them) andeffective_end = NO_OVERLAP_END(soget_overlapsignores them).class Calendar: def add_event(self, event_id: str, start: int, end: int) -> None: # If event_id already exists, clear its old slot first before activating the new one. self.delete_event(event_id) self.events[event_id] = (start, end) # max(q_start, start) < min(q_end, end) requires start < end; zero/inverted intervals # still appear in pagination (count = 1) but can never overlap (effective_end = -inf). if start < end: effective_end: float = float(end) else: effective_end = NO_OVERLAP_END slot = self.slot_of[(start, event_id)] self._update_slot(slot, 1, effective_end) def delete_event(self, event_id: str) -> None: if event_id not in self.events: return old_start, _ = self.events.pop(event_id) old_slot = self.slot_of[(old_start, event_id)] self._update_slot(old_slot, 0, NO_OVERLAP_END)Answer overlap queries with prefix binary search + `max_end` pruning
Now check our four overlap conditions on
get_overlaps(start, end):start < end: ifstart >= end, return[]immediately.e_start < e_end: already enforced because invalid events storedNO_OVERLAP_END(-inf).e_start < end: becauseself.keysis sorted by(e_start, event_id),bisect_left(self.keys, (end, ""))finds the exact cutoff indexprefix_limitwheree_start >= endbegins. Every candidate lies in slots[0, prefix_limit).e_end > start:_collect_overlapsexplores left-to-right and prunes any node immediately iflo >= prefix_limitorself.max_end[node] <= start.
Because we recurse into the left child before the right child, every matching leaf is visited in
(start, event_id)order with no post-sorting needed!from bisect import bisect_left from typing import List class Calendar: def get_overlaps(self, start: int, end: int) -> List[str]: # An empty or inverted query window [start, end) cannot satisfy start < end. if start >= end: return [] # Slots [0, prefix_limit) are the exact keys with event_start < end (half-open boundary). prefix_limit = bisect_left(self.keys, (end, "")) overlapping_ids: List[str] = [] self._collect_overlaps(1, 0, self.size, prefix_limit, start, overlapping_ids) return overlapping_ids def _collect_overlaps( self, node: int, lo: int, hi: int, prefix_limit: int, query_start: int, overlapping_ids: List[str], ) -> None: """Append active event IDs in slots [lo, hi) with slot < prefix_limit and end > query_start.""" # Prune if all slots here start at/after query_end, or no active event ends after query_start. if lo >= prefix_limit or self.max_end[node] <= query_start: return # At a leaf node, both event_start < query_end and event_end > query_start hold. if node >= self.size: event_id = self.keys[lo][1] overlapping_ids.append(event_id) return mid = (lo + hi) // 2 self._collect_overlaps(2 * node, lo, mid, prefix_limit, query_start, overlapping_ids) self._collect_overlaps(2 * node + 1, mid, hi, prefix_limit, query_start, overlapping_ids)Answer pagination queries by descending subtree `count`s
Page
page_numberof sizepage_sizewants active events at 0-based positionsrankfrompage_number * page_sizeup tomin((page_number + 1) * page_size, total_active) - 1.How does
_slot_with_rank(rank)find therank-th active event inO(log M)time? Start at rootnode = 1and comparerankagainstself.count[left_child]:Find rank = 2 in Example 2 (active slots: 0 -> "standup", 1 -> "kickoff", 2 -> "plan"): - At node 1: left_child (node 2) has count = 2. Since 2 is NOT > rank (2), skip those 2 events: rank = 2 - 2 = 0, go right to node 3. - At node 3: left_child (slot 2) has count = 1. Since 1 > rank (0), go left to slot 2 -> keys[2] = (80, "plan")!from typing import List class Calendar: def get_page(self, page_number: int, page_size: int) -> List[str]: if page_number < 0 or page_size <= 0: return [] total_active = self.count[1] first_rank = page_number * page_size last_rank = min(first_rank + page_size, total_active) page_ids: List[str] = [] for rank in range(first_rank, last_rank): slot = self._slot_with_rank(rank) event_id = self.keys[slot][1] page_ids.append(event_id) return page_ids def _slot_with_rank(self, rank: int) -> int: """Return the slot index of the active event at 0-based position `rank`.""" node = 1 while node < self.size: left_child = 2 * node if self.count[left_child] > rank: node = left_child else: # Skip all active events in the left child and search the right child. rank -= self.count[left_child] node = left_child + 1 return node - self.sizeFull solution
Finally,
process_calendar_operationscollects all(start, event_id)keys in one quick pass, buildsCalendar(candidate_keys), and replays every operation:from typing import Any, Dict, List, Optional, Set, Tuple from bisect import bisect_left # Sentinel end time for empty tree slots and zero/inverted events so they never match a query. NO_OVERLAP_END = float("-inf") class Calendar: """In-memory calendar backed by a segment tree over sorted (start, event_id) slots.""" def __init__(self, candidate_keys: List[Tuple[int, str]]) -> None: # Phase 1: Coordinate-compress every (start, event_id) pair that may ever be added. # keys: sorted unique [(start, event_id), ...], e.g. [(75, "standup"), (80, "kickoff"), (80, "plan")] self.keys: List[Tuple[int, str]] = sorted(set(candidate_keys)) # slot_of: {(start, event_id): leaf_slot_index} for O(1) slot lookup on add/delete. self.slot_of: Dict[Tuple[int, str], int] = {} for slot_index, key in enumerate(self.keys): self.slot_of[key] = slot_index # Round leaf count up to a power of two so node 1 is the root and slot s lives at size + s. self.size = 1 while self.size < len(self.keys): self.size *= 2 # count[node]: number of active events inside node's slot range (for O(log M) pagination). # max_end[node]: largest end time among active valid events in node's range (for pruning). self.count: List[int] = [0] * (2 * self.size) self.max_end: List[float] = [NO_OVERLAP_END] * (2 * self.size) # events: {event_id: (start, end)} for O(1) lookup of an existing ID during delete/update. self.events: Dict[str, Tuple[int, int]] = {} def _update_slot(self, slot: int, active_count: int, effective_end: float) -> None: """Write leaf `slot` and recompute count and max_end up to the root in O(log M) time.""" node = self.size + slot self.count[node] = active_count self.max_end[node] = effective_end node //= 2 while node >= 1: left_child = 2 * node right_child = left_child + 1 self.count[node] = self.count[left_child] + self.count[right_child] self.max_end[node] = max(self.max_end[left_child], self.max_end[right_child]) node //= 2 def add_event(self, event_id: str, start: int, end: int) -> None: # If event_id already exists, clear its old slot first before activating the new one. self.delete_event(event_id) self.events[event_id] = (start, end) # max(q_start, start) < min(q_end, end) requires start < end; zero/inverted intervals # still appear in pagination (count = 1) but can never overlap (effective_end = -inf). if start < end: effective_end: float = float(end) else: effective_end = NO_OVERLAP_END slot = self.slot_of[(start, event_id)] self._update_slot(slot, 1, effective_end) def delete_event(self, event_id: str) -> None: if event_id not in self.events: return old_start, _ = self.events.pop(event_id) old_slot = self.slot_of[(old_start, event_id)] self._update_slot(old_slot, 0, NO_OVERLAP_END) def get_overlaps(self, start: int, end: int) -> List[str]: # An empty or inverted query window [start, end) cannot satisfy start < end. if start >= end: return [] # Slots [0, prefix_limit) are the exact keys with event_start < end (half-open boundary). prefix_limit = bisect_left(self.keys, (end, "")) overlapping_ids: List[str] = [] self._collect_overlaps(1, 0, self.size, prefix_limit, start, overlapping_ids) return overlapping_ids def _collect_overlaps( self, node: int, lo: int, hi: int, prefix_limit: int, query_start: int, overlapping_ids: List[str], ) -> None: """Append active event IDs in slots [lo, hi) with slot < prefix_limit and end > query_start.""" # Prune if all slots here start at/after query_end, or no active event ends after query_start. if lo >= prefix_limit or self.max_end[node] <= query_start: return # At a leaf node, both event_start < query_end and event_end > query_start hold. if node >= self.size: event_id = self.keys[lo][1] overlapping_ids.append(event_id) return mid = (lo + hi) // 2 self._collect_overlaps(2 * node, lo, mid, prefix_limit, query_start, overlapping_ids) self._collect_overlaps(2 * node + 1, mid, hi, prefix_limit, query_start, overlapping_ids) def get_page(self, page_number: int, page_size: int) -> List[str]: if page_number < 0 or page_size <= 0: return [] total_active = self.count[1] first_rank = page_number * page_size last_rank = min(first_rank + page_size, total_active) page_ids: List[str] = [] for rank in range(first_rank, last_rank): slot = self._slot_with_rank(rank) event_id = self.keys[slot][1] page_ids.append(event_id) return page_ids def _slot_with_rank(self, rank: int) -> int: """Return the slot index of the active event at 0-based position `rank`.""" node = 1 while node < self.size: left_child = 2 * node if self.count[left_child] > rank: node = left_child else: # Skip all active events in the left child and search the right child. rank -= self.count[left_child] node = left_child + 1 return node - self.size def process_calendar_operations(operations: List[str], arguments: List[List]) -> List: # Pre-scan all add_event calls so the segment tree has a slot for every possible (start, id). candidate_keys: List[Tuple[int, str]] = [] for op, args in zip(operations, arguments): if op == "add_event": event_id, start, _ = args candidate_keys.append((start, event_id)) calendar = Calendar(candidate_keys) # Execute operations in sequence and record each method's return value (None for mutations). results: List[Any] = [] for op, args in zip(operations, arguments): if op == "add_event": calendar.add_event(args[0], args[1], args[2]) results.append(None) elif op == "delete_event": calendar.delete_event(args[0]) results.append(None) elif op == "get_overlaps": results.append(calendar.get_overlaps(args[0], args[1])) elif op == "get_page": results.append(calendar.get_page(args[0], args[1])) else: raise ValueError(f"Unknown operation: {op!r}") return results✅ Submit now — all tests should pass.
Intuition & how it works
Picture a large appointment binder whose numbered lines are already printed in chronological (start, event_id) order and grouped into chapters and sub-chapters. On the cover of every chapter tab, you pencil two tiny sticky notes:
1. count: how many appointments inside this chapter are currently active, and
2. max_end: the latest ending time among all active appointments inside this chapter.
That hierarchical summary is a segment tree (a binary tree built over an array where each internal node maintains aggregate summaries for a contiguous slice of array slots). Because the batch runner provides all operations up front, we first use coordinate compression (collecting every (start, event_id) pair that will ever be added, sorting the unique pairs once, and mapping each pair to a compact integer slot 0 .. M - 1). Each event is a half-open interval [start, end) — meaning start is included and end is excluded, so [5, 15) and [15, 25) touch at 15 without overlapping. Empty slots and non-positive intervals store a sentinel value (float("-inf"), a special marker guaranteed to be smaller than every valid timestamp) as their end time.
Why do simpler structures hit a wall at N = 10^5? Keeping only a dictionary event_id -> (start, end) makes updates O(1), but every get_page must sort all N events in O(N log N) time and every get_overlaps must scan all N events in O(N) time — roughly 10^10 steps across 10^5 queries. Keeping a sorted Python list makes pagination slicing fast, but inserting or deleting in the middle shifts O(N) elements on every write. With the two-summary segment tree, updates touch one root-to-leaf path in O(log M) time, pagination uses an order-statistic walk (descending left or right by comparing rank against count[left_child]), and overlap queries binary-search the prefix of events with event_start < query_end and prune whole subtrees wherever max_end <= query_start.
Let's trace adding the three events from Example 1 (sync=[30, 50), demo=[40, 65), retro=[50, 70)) and running both query types:
Add: sync=[30, 50), demo=[40, 65), retro=[50, 70)
Sorted slots: slot 0 = (30, "sync") end 50 | slot 1 = (40, "demo") end 65 | slot 2 = (50, "retro") end 70
1. get_page(page_number=0, page_size=2):
Wants ranks 0 and 1 -> descends tree by `count` -> slots 0 and 1 -> ["sync", "demo"]
2. get_overlaps(start=35, end=50):
- Prefix with event_start < 50: bisect_left stops before (50, "retro") -> slots [0, 2)
- Slot 0 ("sync"): end 50 > 35 -> keep "sync"
- Slot 1 ("demo"): end 65 > 35 -> keep "demo"
- Slot 2 ("retro"): lo=2 >= prefix_limit=2 -> pruned immediately!
Result: ["sync", "demo"]
Complexity
Let M be the number of unique (start, event_id) keys across all add_event calls (M <= 10^5), K be the number of overlapping events returned by get_overlaps, and P be page_size.
- Initial setup:
O(M log M)time. Collecting, deduplicating, and sorting up toMcandidate keys takesO(M log M), and initializing the tree arrays of length<= 4MtakesO(M). add_eventanddelete_event:O(log M)average time. Looking upevent_idinself.eventsand(start, event_id)inself.slot_ofareO(1)average dictionary operations, and_update_slotupdates one leaf and itsO(log M)ancestors.get_overlaps:O((K + 1) log M)time.bisect_leftfindsprefix_limitinO(log M). During_collect_overlaps, at most one node per tree level straddlesprefix_limit(O(log M)nodes total); every other unpruned subtree lies strictly left ofprefix_limit(event_start < query_end) and hasmax_end > query_start, guaranteeing at least one reported overlap inside it (O(K log M)nodes across allKhits).get_page:O(min(P, N) * log M)time. For each of the at mostPitems on the requested page,_slot_with_rankwalks one root-to-leaf path of heightO(log M).- Space:
O(M).self.keys,self.slot_of,self.events,self.count, andself.max_endare all bounded by a small constant multiple ofM.
Edge cases
- Touching half-open boundaries (
[5, 15)vs.[15, 25)): Do not overlap.bisect_left(self.keys, (end, ""))excludes events withevent_start == end, andself.max_end[node] <= query_startexcludes events withevent_end == start. - Zero-length (
[5, 5)) and inverted ([20, 10)) events:max(q_start, e_start) < min(q_end, e_end)requirese_start < e_end, so these events never overlap anything (effective_end = -inf), yet they remain active (count = 1) and appear inget_page. - Zero-length or inverted query (
start >= end): Guarded at the top ofget_overlapsand immediately returns[]. - Updating an existing
event_id:add_eventcallsdelete_event(event_id)first, clearing the old slot so the event never appears twice on pages or retains a ghost interval. - Deleting a non-existent
event_id:if event_id not in self.events: returnmakes it a safe no-op. - Out-of-range pagination (
page_numberpast the last page,page_number < 0, orpage_size <= 0): Returns[]; a partially filled final page clampslast_ranktoself.count[1]. - Calendar with zero
add_eventcalls:self.sizedefaults to1withcount[1] == 0, so all queries safely return[].
Common mistakes
- Checking only
e_start < q_end and e_end > q_startwithout checkinge_start < e_endandq_start < q_end: That simplified 2-part check assumes valid positive intervals; on a zero-length event[5, 5)and query[0, 10)it evaluates5 < 10 and 5 > 0 -> True, violatingmax(0, 5) < min(10, 5)(5 < 5isFalse). - Forgetting to clear the old slot when
add_eventupdates an existing ID: Leaves stale data in the tree, causing duplicate IDs inget_pageand phantom overlaps at the old time window. - Using
<instead of<=when pruningmax_end(self.max_end[node] < query_start): Fails to prune events that end atquery_start, falsely reporting touching half-open intervals as overlapping. - Using
-1instead of-infas the empty-slot sentinel: Breaks if a query passesstart = -1or negative timestamps;float("-inf")is smaller than every integer. - Scanning every slot in
[0, prefix_limit)withoutmax_endpruning: Degradesget_overlapsback toO(N)per query whenever a narrow query happens near the end of the timeline.
Alternative approaches
- Online augmented balanced binary search tree (Treap / Red-Black Tree): When operations arrive live one at a time instead of as a batch, we cannot pre-collect
candidate_keys. Maintaining a balanced binary search tree (a self-balancing tree that keeps heightO(log N)under arbitrary insertions and deletions) keyed by(start, event_id)and storing(subtree_count, subtree_max_end)on each node supports the exact sameO(log N)updates,O((K + 1) log N)pruned overlap queries, andO(P log N)rank lookups completely online.
Follow-up questions
- How would you adapt the data model to handle repeating schedules (such as weekly meetings) without expanding every future instance in memory? Never materialize thousands of copies per rule; instead, store each recurring rule compactly as
(event_id, first_start, duration, period, until_time)plus an exception map keyed by(event_id, occurrence_start)for edited or cancelled single dates. Index each series in the interval structure by its bounding envelope[first_start, until_time + duration), and whenget_overlaps(a, b)hits a series envelope, use modular arithmetic (k = max(0, ceil((a - duration - first_start) / period))) to generate only the occurrences inside[a, b). For pagination, unbounded recurring rules have infinitely many future instances, soget_pagemust require a finite horizon window[window_start, window_end)and merge individual events with series occurrences lazily using a min-heap. - Suppose queries outnumber writes by orders of magnitude; how could you speed up
get_pageby precomputing or caching sorted slices? Maintain a flat, contiguous sorted arrayordered_idsof(start, event_id):get_page(p, k)becomes a zero-overhead array sliceordered_ids[p * k : (p + 1) * k]inO(k)time rather thanO(k log N)tree descents. If callers repeatedly request standard page sizes (likepage_size = 20or50), you can also cache pre-sliced immutable tuples tagged with a monotonically increasingwrite_versioncounter so writes simply incrementwrite_version(invalidating stale cache entries inO(1)) and insert/remove the changed key in the flat array inO(N)time. - What concurrency controls would you introduce so concurrent readers and writers can safely share the calendar across multiple threads? Because every write mutates both
self.eventsand the tree nodes, an unprotected reader could observe a half-updated state (such as an updated event temporarily missing right afterdelete_eventclears its old slot). Wrapping the calendar in a readers-writer lock (a synchronization primitive allowing arbitrarily many concurrentget_overlaps/get_pagereaders, whileadd_event/delete_eventwriters acquire exclusive access) keeps reads parallel and mutations atomic. At multi-tenant scale, shard calendars byuser_idorcalendar_idso each user's calendar has its own independent lock with zero cross-user contention, or use persistent copy-on-write tree nodes so readers lock-freely read an immutable root pointer while writers atomically swap in a new root.
Follow-up questions
- How would you adapt the data model to handle repeating schedules (such as weekly meetings) without expanding every future instance in memory?
- Suppose queries outnumber writes by orders of magnitude; how could you speed up `get_page` by precomputing or caching sorted slices?
- What concurrency controls would you introduce so concurrent readers and writers can safely share the calendar across multiple threads?
Similar questions
- Versioned Key-Value Store with Snapshots
- Time-Series Stock Quote Store
- Mutable Ticker Price Ledger
- Timestamped Key-Value Store and Mutual-Friend Recommendations
- Distributed Hotel Room Search and Booking Architecture
- Room-Level Hotel Booking Without Overlapping Stays
More Lead Bank interview questions
- Room-Level Hotel Booking Without Overlapping Stays Medium
- Time-Series Stock Quote Store Medium
- Mutable Ticker Price Ledger Medium Pro
- Distributed Hotel Room Search and Booking Architecture Medium Pro
- Balancing PM Deadlines and AI Code Safety in Financial Systems Medium Pro
- Versioned Key-Value Store with Snapshots Medium Pro
- Timestamped Key-Value Store and Mutual-Friend Recommendations Medium Pro