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]:

  1. "add_event" with [event_id, start, end]: Inserts (event_id, start, end) into the calendar, or replaces its interval if event_id is already present. Appends None to the returned list.
  2. "delete_event" with [event_id]: Removes event_id if it exists; does nothing if event_id is absent. Appends None to the returned list.
  3. "get_overlaps" with [start, end]: Returns all active event_ids whose interval [event_start, event_end) overlaps [start, end) according to max(start, event_start) < min(end, event_end), ordered by ascending event_start and then alphabetically (<) by event_id.
  4. "get_page" with [page_number, page_size]: Orders all currently active events by ascending start time and breaks ties alphabetically (<) by event_id, returning the event_ids on 0-indexed page page_number of size page_size (or [] when page_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^5 total operations and up to 10^5 active events
  • 0 <= start, end <= 10^9 (zero-length or inverted intervals with start >= end may appear)
  • page_number is 0-indexed; out-of-range pages return []
  • Both "get_page" and "get_overlaps" return event_ids ordered by (start, event_id)

Step-by-step walkthrough

  1. Unpack the half-open overlap rule and page order

    Our Calendar manages events with IDs and half-open intervals [start, end), driven by process_calendar_operations(operations, arguments):

    • add_event(id, start, end) -> adds or updates id (returns None).
    • delete_event(id) -> removes id if present (returns None).
    • get_overlaps(q_start, q_end) -> returns all overlapping event_ids.
    • get_page(page_number, page_size) -> returns the 0-indexed page of event_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 in get_page), but condition #2 (e_start < e_end) means they never overlap any query. - Returning get_overlaps in the same (start, event_id) order as get_page keeps all outputs deterministic and matches Example 1 (["sync", "demo"]).

  2. Why sorting or scanning on every query is too slow

    A simple reference implementation keeps events = {event_id: (start, end)} and sorts or scans events on each query.

    With up to N = 10^5 events and 10^5 operations: - Re-sorting on every get_page takes O(N log N) per query (~10^10+ steps total). - Scanning every event on every get_overlaps takes O(N) per query — even when a narrow query like [14, 16) only hits 1 or 2 events! - Keeping a plain sorted Python list makes page slicing fast, but inserting or deleting in the middle shifts up to N elements in O(N) time.

    We need a structure sorted by (start, event_id) where insertions and deletions take O(log N) time, pagination jumps straight to any rank, and overlap search skips whole blocks of non-overlapping events.

  3. Key idea: a segment tree over sorted `(start, event_id)` slots

    Because process_calendar_operations gives us the entire list of operations up front, we can pre-scan all add_event calls, collect every (start, event_id) pair that could ever exist, sort unique pairs once into self.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 by get_page to jump to the k-th event), - max_end[node]: the largest end among active positive-length events in this subtree, or -inf if none (used by get_overlaps to skip an entire subtree whenever max_end[node] <= q_start).

    Here is what the tree looks like after all four add_event calls in Example 2 (standup updated 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=-inf
    
  4. Build the slot index and bottom-up update helper

    We round the leaf capacity self.size up to the next power of two so the tree fits cleanly in flat arrays of length 2 * self.size: - Node 1 is the root. - Node i has left child 2 * i and right child 2 * i + 1. - Leaf slot lives at array index self.size + slot.

    Whenever a slot turns on (active_count = 1) or off (active_count = 0), _update_slot writes the leaf and walks up node //= 2 to recompute its O(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 //= 2
    
  5. Implement `add_event` and `delete_event`

    self.events maps each active event_id to (start, end) so delete_event can find its old start in O(1) time and switch off (old_start, event_id).

    Calling self.delete_event(event_id) at the start of add_event handles 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 set active_count = 1 (so get_page still counts them) and effective_end = NO_OVERLAP_END (so get_overlaps ignores 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)
    
  6. Answer overlap queries with prefix binary search + `max_end` pruning

    Now check our four overlap conditions on get_overlaps(start, end):

    1. start < end: if start >= end, return [] immediately.
    2. e_start < e_end: already enforced because invalid events stored NO_OVERLAP_END (-inf).
    3. e_start < end: because self.keys is sorted by (e_start, event_id), bisect_left(self.keys, (end, "")) finds the exact cutoff index prefix_limit where e_start >= end begins. Every candidate lies in slots [0, prefix_limit).
    4. e_end > start: _collect_overlaps explores left-to-right and prunes any node immediately if lo >= prefix_limit or self.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)
    
  7. Answer pagination queries by descending subtree `count`s

    Page page_number of size page_size wants active events at 0-based positions rank from page_number * page_size up to min((page_number + 1) * page_size, total_active) - 1.

    How does _slot_with_rank(rank) find the rank-th active event in O(log M) time? Start at root node = 1 and compare rank against self.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.size
    
  8. Full solution

    Finally, process_calendar_operations collects all (start, event_id) keys in one quick pass, builds Calendar(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 to M candidate keys takes O(M log M), and initializing the tree arrays of length <= 4M takes O(M).
  • add_event and delete_event: O(log M) average time. Looking up event_id in self.events and (start, event_id) in self.slot_of are O(1) average dictionary operations, and _update_slot updates one leaf and its O(log M) ancestors.
  • get_overlaps: O((K + 1) log M) time. bisect_left finds prefix_limit in O(log M). During _collect_overlaps, at most one node per tree level straddles prefix_limit (O(log M) nodes total); every other unpruned subtree lies strictly left of prefix_limit (event_start < query_end) and has max_end > query_start, guaranteeing at least one reported overlap inside it (O(K log M) nodes across all K hits).
  • get_page: O(min(P, N) * log M) time. For each of the at most P items on the requested page, _slot_with_rank walks one root-to-leaf path of height O(log M).
  • Space: O(M). self.keys, self.slot_of, self.events, self.count, and self.max_end are all bounded by a small constant multiple of M.

Edge cases

  • Touching half-open boundaries ([5, 15) vs. [15, 25)): Do not overlap. bisect_left(self.keys, (end, "")) excludes events with event_start == end, and self.max_end[node] <= query_start excludes events with event_end == start.
  • Zero-length ([5, 5)) and inverted ([20, 10)) events: max(q_start, e_start) < min(q_end, e_end) requires e_start < e_end, so these events never overlap anything (effective_end = -inf), yet they remain active (count = 1) and appear in get_page.
  • Zero-length or inverted query (start >= end): Guarded at the top of get_overlaps and immediately returns [].
  • Updating an existing event_id: add_event calls delete_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: return makes it a safe no-op.
  • Out-of-range pagination (page_number past the last page, page_number < 0, or page_size <= 0): Returns []; a partially filled final page clamps last_rank to self.count[1].
  • Calendar with zero add_event calls: self.size defaults to 1 with count[1] == 0, so all queries safely return [].

Common mistakes

  • Checking only e_start < q_end and e_end > q_start without checking e_start < e_end and q_start < q_end: That simplified 2-part check assumes valid positive intervals; on a zero-length event [5, 5) and query [0, 10) it evaluates 5 < 10 and 5 > 0 -> True, violating max(0, 5) < min(10, 5) (5 < 5 is False).
  • Forgetting to clear the old slot when add_event updates an existing ID: Leaves stale data in the tree, causing duplicate IDs in get_page and phantom overlaps at the old time window.
  • Using < instead of <= when pruning max_end (self.max_end[node] < query_start): Fails to prune events that end at query_start, falsely reporting touching half-open intervals as overlapping.
  • Using -1 instead of -inf as the empty-slot sentinel: Breaks if a query passes start = -1 or negative timestamps; float("-inf") is smaller than every integer.
  • Scanning every slot in [0, prefix_limit) without max_end pruning: Degrades get_overlaps back to O(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 height O(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 same O(log N) updates, O((K + 1) log N) pruned overlap queries, and O(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 when get_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, so get_page must 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_page by precomputing or caching sorted slices? Maintain a flat, contiguous sorted array ordered_ids of (start, event_id): get_page(p, k) becomes a zero-overhead array slice ordered_ids[p * k : (p + 1) * k] in O(k) time rather than O(k log N) tree descents. If callers repeatedly request standard page sizes (like page_size = 20 or 50), you can also cache pre-sliced immutable tuples tagged with a monotonically increasing write_version counter so writes simply increment write_version (invalidating stale cache entries in O(1)) and insert/remove the changed key in the flat array in O(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.events and the tree nodes, an unprotected reader could observe a half-updated state (such as an updated event temporarily missing right after delete_event clears its old slot). Wrapping the calendar in a readers-writer lock (a synchronization primitive allowing arbitrarily many concurrent get_overlaps / get_page readers, while add_event / delete_event writers acquire exclusive access) keeps reads parallel and mutations atomic. At multi-tenant scale, shard calendars by user_id or calendar_id so 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

Similar questions

More Lead Bank interview questions

All 8 Lead Bank questions →