In-Memory Calendar Service and Interval Queries
Data Structure DesignModel answerLast updated
Design and implement an in-memory calendar event service with full CRUD operations, validation rules, conflict detection, and unit testing strategy.
Design an in-memory calendar service class that manages single-user or team calendar entries. The service must support complete CRUD operations, enforce data validation constraints, execute interval queries, and support target conflict checks.
Class Definition
from typing import List, Optional
class Event:
def __init__(self, event_id: str, title: str, start_time: int, end_time: int, attendees: List[str]):
self.id = event_id
self.title = title
self.start_time = start_time # Non-negative integer (Unix timestamp in seconds)
self.end_time = end_time # Non-negative integer (Unix timestamp in seconds)
self.attendees = attendees
class CalendarService:
def create_event(self, title: str, start_time: int, end_time: int, attendees: List[str]) -> Event:
"""Creates and stores a new event. Raises ValueError if validation fails."""
pass
def get_event(self, event_id: str) -> Optional[Event]:
"""Retrieves an event by its unique ID. Returns None if not found."""
pass
def update_event(self, event_id: str, title: Optional[str] = None,
start_time: Optional[int] = None, end_time: Optional[int] = None,
attendees: Optional[List[str]] = None) -> Event:
"""Updates attributes of an existing event.
Raises KeyError if the event doesn't exist.
Raises ValueError if updated state breaks validation rules.
"""
pass
def delete_event(self, event_id: str) -> bool:
"""Deletes an event by ID. Returns True if removed, False if not found."""
pass
def get_events_in_range(self, start_time: int, end_time: int) -> List[Event]:
"""Returns all events overlapping [start_time, end_time], sorted by start_time ascending."""
pass
def find_conflicts(self, user: str, start_time: int, end_time: int, exclude_event_id: Optional[str] = None) -> List[Event]:
"""Returns all events involving `user` that overlap [start_time, end_time],
ignoring `exclude_event_id` if provided. Sorted by start_time ascending.
"""
pass
Specifications & Rules
- Validation Requirements:
start_timemust be strictly less thanend_time(start_time < end_time).- Timestamps must be non-negative integers.
titlemust be a non-empty, non-whitespace-only string.attendeesmust be a list of strings.
- Interval Overlap Definition:
- Half-open interval definition: two periods $[s_1, e_1]$ and $[s_2, e_2]$ overlap if and only if $\max(s_1, s_2) < \min(e_1, e_2)$.
- Touching boundaries ($e_1 = s_2$ or $e_2 = s_1$) do not overlap.
- Atomicity:
- Partial updates using
update_eventmust validate the full resulting event state prior to mutation. If validation fails, no changes should persist.
- Partial updates using
- Ordering:
- Result lists from
get_events_in_rangeandfind_conflictsmust be sorted primarily bystart_timeascending, secondarily byend_timeascending, and finally byevent_idascending.
- Result lists from
Example
service = CalendarService()
# Create two events
e1 = service.create_event("Team Standup", 100, 200, ["[email protected]", "[email protected]"])
e2 = service.create_event("Design Review", 200, 300, ["[email protected]"])
# Querying range [150, 250]: e1 ([100, 200]) and e2 ([200, 300]) both overlap [150, 250]
events_in_range = service.get_events_in_range(150, 250)
assert len(events_in_range) == 2
# Checking conflicts for candidate interval [200, 250] for Alice, excluding e2:
# e1 ends at 200, candidate starts at 200 -> touching boundary, no overlap.
conflicts = service.find_conflicts("[email protected]", 200, 250, exclude_event_id=e2.id)
assert len(conflicts) == 0
Hints
Hint 1
Consolidate event attribute validation into a single private method shared by `create_event` and `update_event` to guarantee identical business rules across state changes.
Hint 2
To ensure transactional safety in `update_event`, create a merged hypothetical state first, validate it, and only modify the underlying dictionary if validation succeeds.
Hint 3
Two time windows [s1, e1] and [s2, e2] overlap if and only if `max(s1, s2) < min(e1, e2)`.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach & Architecture
To design a clean, maintainable CalendarService, we focus on code reuse, strong transactional boundaries, and well-defined helper functions.
- Storage Structure: An internal dictionary
_events: Dict[str, Event]maps unique event IDs generated viauuid.uuid4().hextoEventinstances. This gives $O(1)$ lookup, update, and deletion performance. - Centralized Validation: A static/class helper
_validatecentralizes parameter checking for title, start/end bounds, type checks, and non-negative constraints. - Atomic Updates: When performing partial updates with
update_event, we merge existing values with non-Noneparameter arguments to construct the target state. We validate this prospective object before mutating the stored record, ensuring failed updates leave the data unchanged. - Overlap Math: Interval intersection between $[s_1, e_1]$ and $[s_2, e_2]$ is determined by evaluating $\max(s_1, s_2) < \min(e_1, e_2)$. Using strict inequality
<ensures contiguous back-to-back meetings ($e_1 = s_2$) do not trigger an overlap. - Defensive Storage: Inputs containing mutable lists (like
attendees) are copied (list(attendees)) upon entry so external modifications to caller arguments do not leak into internal storage.
Python Implementation
import uuid
from typing import List, Optional, Dict
class Event:
def __init__(self, event_id: str, title: str, start_time: int, end_time: int, attendees: List[str]):
self.id = event_id
self.title = title
self.start_time = start_time
self.end_time = end_time
self.attendees = attendees
class CalendarService:
def __init__(self):
self._events: Dict[str, Event] = {}
# ---------------- Validation Helpers ----------------
@staticmethod
def _is_valid_timestamp(ts: int) -> bool:
# Exclude booleans because bool is a subclass of int in Python
return isinstance(ts, int) and not isinstance(ts, bool) and ts >= 0
@classmethod
def _validate(cls, title: str, start_time: int, end_time: int, attendees: List[str]) -> None:
if not isinstance(title, str) or not title.strip():
raise ValueError("Title must be a non-empty string.")
if not cls._is_valid_timestamp(start_time) or not cls._is_valid_timestamp(end_time):
raise ValueError("Timestamps must be non-negative integers.")
if start_time >= end_time:
raise ValueError("start_time must be strictly less than end_time.")
if not isinstance(attendees, list) or not all(isinstance(a, str) for a in attendees):
raise ValueError("Attendees must be a list of strings.")
@staticmethod
def _overlaps(s1: int, e1: int, s2: int, e2: int) -> bool:
return max(s1, s2) < min(e1, e2)
@staticmethod
def _sort_key(event: Event):
return (event.start_time, event.end_time, event.id)
# ---------------- CRUD Operations ----------------
def create_event(self, title: str, start_time: int, end_time: int, attendees: List[str]) -> Event:
self._validate(title, start_time, end_time, attendees)
event_id = uuid.uuid4().hex
event = Event(
event_id=event_id,
title=title.strip(),
start_time=start_time,
end_time=end_time,
attendees=list(attendees)
)
self._events[event_id] = event
return event
def get_event(self, event_id: str) -> Optional[Event]:
return self._events.get(event_id)
def update_event(
self,
event_id: str,
title: Optional[str] = None,
start_time: Optional[int] = None,
end_time: Optional[int] = None,
attendees: Optional[List[str]] = None
) -> Event:
existing = self._events.get(event_id)
if existing is None:
raise KeyError(f"Event with ID {event_id} does not exist.")
# Compute new potential field values
new_title = existing.title if title is None else title
new_start = existing.start_time if start_time is None else start_time
new_end = existing.end_time if end_time is None else end_time
new_attendees = existing.attendees if attendees is None else attendees
# Validate proposed state prior to mutation
self._validate(new_title, new_start, new_end, new_attendees)
# Apply state changes atomically
existing.title = new_title.strip()
existing.start_time = new_start
existing.end_time = new_end
existing.attendees = list(new_attendees)
return existing
def delete_event(self, event_id: str) -> bool:
return self._events.pop(event_id, None) is not None
# ---------------- Query Operations ----------------
def get_events_in_range(self, start_time: int, end_time: int) -> List[Event]:
if not self._is_valid_timestamp(start_time) or not self._is_valid_timestamp(end_time):
raise ValueError("Query timestamps must be non-negative integers.")
if start_time >= end_time:
raise ValueError("Query start_time must be strictly less than end_time.")
matches = [
e for e in self._events.values()
if self._overlaps(e.start_time, e.end_time, start_time, end_time)
]
return sorted(matches, key=self._sort_key)
def find_conflicts(
self,
user: str,
start_time: int,
end_time: int,
exclude_event_id: Optional[str] = None
) -> List[Event]:
if not self._is_valid_timestamp(start_time) or not self._is_valid_timestamp(end_time):
raise ValueError("Query timestamps must be non-negative integers.")
if start_time >= end_time:
raise ValueError("Query start_time must be strictly less than end_time.")
conflicts = [
e for e in self._events.values()
if e.id != exclude_event_id
and user in e.attendees
and self._overlaps(e.start_time, e.end_time, start_time, end_time)
]
return sorted(conflicts, key=self._sort_key)
Comprehensive Unit Test Suite
import unittest
class TestCalendarService(unittest.TestCase):
def setUp(self):
self.service = CalendarService()
def test_create_and_get_event_success(self):
event = self.service.create_event("Sync", 10, 20, ["userA"])
fetched = self.service.get_event(event.id)
self.assertIsNotNone(fetched)
self.assertEqual(fetched.title, "Sync")
self.assertEqual(fetched.start_time, 10)
self.assertEqual(fetched.end_time, 20)
self.assertEqual(fetched.attendees, ["userA"])
def test_invalid_create_parameters(self):
# Invalid title
with self.assertRaises(ValueError):
self.service.create_event(" ", 10, 20, ["userA"])
# Invalid time sequence (start >= end)
with self.assertRaises(ValueError):
self.service.create_event("Sync", 20, 10, ["userA"])
with self.assertRaises(ValueError):
self.service.create_event("Sync", 10, 10, ["userA"])
# Boolean type trap
with self.assertRaises(ValueError):
self.service.create_event("Sync", True, 10, ["userA"])
def test_update_atomic_rollback(self):
event = self.service.create_event("Sync", 100, 200, ["userA"])
# Attempt an invalid update (start_time 250 > current end_time 200)
with self.assertRaises(ValueError):
self.service.update_event(event.id, start_time=250)
# Verify state remained completely unchanged
refreshed = self.service.get_event(event.id)
self.assertEqual(refreshed.start_time, 100)
self.assertEqual(refreshed.end_time, 200)
def test_delete_event(self):
event = self.service.create_event("Sync", 100, 200, ["userA"])
self.assertTrue(self.service.delete_event(event.id))
self.assertIsNone(self.service.get_event(event.id))
self.assertFalse(self.service.delete_event(event.id))
def test_range_query_boundary_touching(self):
# Events: [100, 200] and [200, 300]
e1 = self.service.create_event("E1", 100, 200, ["userA"])
e2 = self.service.create_event("E2", 200, 300, ["userA"])
# Query range [200, 250]: should match E2 only (touching at 200 for E1 does not overlap)
results = self.service.get_events_in_range(200, 250)
self.assertEqual([e.id for e in results], [e2.id])
def test_find_conflicts_with_exclusion(self):
e1 = self.service.create_event("E1", 100, 200, ["userA"])
e2 = self.service.create_event("E2", 150, 250, ["userA"])
# Conflict check for userA over [120, 180] excluding e1
conflicts = self.service.find_conflicts("userA", 120, 180, exclude_event_id=e1.id)
self.assertEqual([e.id for e in conflicts], [e2.id])
if __name__ == "__main__":
unittest.main()
Complexity Analysis
| Operation | Time Complexity | Space Complexity |
|---|---|---|
create_event / get_event / delete_event | $O(1)$ avg | $O(1)$ |
update_event | $O(1)$ avg | $O(1)$ |
get_events_in_range | $O(N + K \log K)$ | $O(K)$ |
find_conflicts | $O(N + K \log K)$ | $O(K)$ |
Where $N$ is the total number of stored events and $K$ is the number of matching events returned by queries. If interval queries need to scale to large datasets ($N \gg 10^5$), the storage model can be backed by an Interval Tree or Segment Tree, reducing query time to $O(\log N + K)$.