KatInterview

In-Memory Calendar Service and Interval Queries

Data Structure DesignModel answer
MediumModel answerData Structure Designdesignintervalscrud

Last 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

  1. Validation Requirements:
    • start_time must be strictly less than end_time (start_time < end_time).
    • Timestamps must be non-negative integers.
    • title must be a non-empty, non-whitespace-only string.
    • attendees must be a list of strings.
  2. 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.
  3. Atomicity:
    • Partial updates using update_event must validate the full resulting event state prior to mutation. If validation fails, no changes should persist.
  4. Ordering:
    • Result lists from get_events_in_range and find_conflicts must be sorted primarily by start_time ascending, secondarily by end_time ascending, and finally by event_id ascending.

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)`.