Pluggable Event Campaign Notification Engine

Medium · Coding & Algorithms · Software Engineer · Onsite

Problem Statement

Design and implement an extensible campaign-dispatch engine for a live-events marketplace. Given a customer profile, a catalog of events, and a reference calendar date today, the engine selects relevant upcoming events across a configurable list of marketing campaigns, formats each alert, and dispatches it through a notification interface.

Data Models & Interfaces

Use the frozen dataclasses and base abstractions in starter.py:

  • Customer(id: int, city: str, birth_month: int, birth_day: int, latitude: float, longitude: float)
  • Event(id: int, title: str, city: str, start_time: datetime, latitude: float, longitude: float)
  • NotificationService.send(customer_id: int, message: str) -> None

Required Functions & Classes

  1. is_upcoming(event: Event, today: date) -> bool:
    • Return True if and only if event.start_time.date() >= today.
  2. next_birthday(birth_month: int, birth_day: int, today: date) -> date:
    • Return the earliest calendar date strictly after today (> today) on which the customer's birthday is observed.
    • A Feb 29 birthday is observed on Feb 28 in non-leap years and Feb 29 in leap years.
  3. Campaign (extensible strategy base class):
    • Class attribute label = "Campaign".
    • select(customer: Customer, events: List[Event], today: date) -> List[Event]: given upcoming events, return the selected events in dispatch order.
    • format_message(customer: Customer, event: Event) -> str: format an event as "[<label>] <title> - <YYYY-MM-DD HH:MM> - <event.city>".
  4. Built-in Campaign subclasses:
    • SameCityCampaign (label = "In your city"): select all upcoming events whose city matches customer.city ignoring surrounding whitespace and letter case (.strip().casefold()), ordered by ascending (event.start_time, event.id).
    • BirthdayCampaign (label = "For your birthday"): select a single-element list containing the upcoming event minimizing abs((event.start_time.date() - next_bday).days) on either side of next_birthday(...), breaking ties by earlier event.start_time, then smaller event.id. Return [] if no upcoming events exist.
    • NearestEventsCampaign(limit: int = 5) (label = "Near you"): raise ValueError if limit < 1. Select up to limit upcoming events closest to (customer.latitude, customer.longitude) under Euclidean distance hypot(d_lat, d_lon), ordered nearest first with ties broken by earlier event.start_time, then smaller event.id (return all upcoming events if fewer than limit exist).
  5. MarketingEngine(notifier: NotificationService, campaigns: Sequence[Campaign]):
    • send_customer_notifications(customer: Customer, events: List[Event], today: date) -> List[str]:
      • Filter events once via is_upcoming(event, today).
      • Execute campaigns in sequence without any campaign-specific if/elif branches inside the engine, so custom Campaign subclasses work unmodified.
      • Format each selected event with campaign.format_message(customer, event), call notifier.send(customer.id, message), and return all sent message strings in dispatch order.

Examples

Example 1

Input:

today = date(2026, 9, 10)
customer = Customer(id=88, city="Austin", birth_month=9, birth_day=25, latitude=0.0, longitude=0.0)
events = [
    Event(10, "Blues Jam", "Austin", datetime(2026, 9, 14, 20, 0), 1.0, 1.0),
    Event(20, "Indie Showcase", "Dallas", datetime(2026, 9, 24, 19, 30), 0.0, 4.0),
    Event(30, "Summer Finale", "Austin", datetime(2026, 9, 1, 18, 0), 0.0, 0.0),
]
campaigns = [SameCityCampaign(), BirthdayCampaign(), NearestEventsCampaign(limit=5)]

Output:

[
    "[In your city] Blues Jam - 2026-09-14 20:00 - Austin",
    "[For your birthday] Indie Showcase - 2026-09-24 19:30 - Dallas",
    "[Near you] Blues Jam - 2026-09-14 20:00 - Austin",
    "[Near you] Indie Showcase - 2026-09-24 19:30 - Dallas",
]

Explanation: - Summer Finale (2026-09-01) precedes today (2026-09-10) and is excluded before any campaign runs. - SameCityCampaign picks Blues Jam in "Austin". - BirthdayCampaign compares next_birthday = 2026-09-25: Indie Showcase (1 day away) beats Blues Jam (11 days away). - NearestEventsCampaign(limit=5) ranks the 2 upcoming events (< 5) by Euclidean distance: sqrt(2) ≈ 1.414 before 4.0.

Example 2

Input:

today = date(2026, 2, 28)
customer = Customer(id=99, city="Denver", birth_month=2, birth_day=29, latitude=0.0, longitude=0.0)
events = [
    Event(1, "Acoustic Set", "Boulder", datetime(2027, 3, 2, 18, 0), 3.0, 4.0),
    Event(2, "Symphony Gala", " denver ", datetime(2027, 2, 26, 20, 0), -3.0, -4.0),
]
campaigns = [SameCityCampaign(), BirthdayCampaign(), NearestEventsCampaign(limit=1)]

Output:

[
    "[In your city] Symphony Gala - 2027-02-26 20:00 -  denver ",
    "[For your birthday] Symphony Gala - 2027-02-26 20:00 -  denver ",
    "[Near you] Symphony Gala - 2027-02-26 20:00 -  denver ",
]

Explanation: - In non-leap 2026, Feb 29 maps to 2026-02-28 == today; since next_birthday must be strictly after today, it advances to non-leap 2027-02-28. - SameCityCampaign matches " denver " case-insensitively after trimming while keeping event.city verbatim in the formatted text. - Both events sit 2 days from 2027-02-28 and 5.0 Euclidean units from (0.0, 0.0), so both BirthdayCampaign and NearestEventsCampaign(limit=1) break ties in favor of the earlier start_time (Event 2).

Constraints

  • 0 <= len(events) <= 10^5.
  • (birth_month, birth_day) is a valid calendar month/day pair (including (2, 29)).
  • Coordinates are finite floats; NearestEventsCampaign requires limit >= 1.

Step-by-step walkthrough

  1. Pin down edge-case rules and data models

    Before writing classes, clarify every open detail of the specification so your design is deterministic and easy to test:

    • Upcoming events: Because today is a calendar date (no clock hour), an event is upcoming when event.start_time.date() >= today. Events starting later today—or earlier on today's calendar date—count; yesterday's events do not.
    • Next birthday strictly after today: "After today" is strict (>). If today is June 20 and the customer's birthday is June 20, their next birthday is June 20 of next year. A leap-day birthday (Feb 29) is celebrated on Feb 28 in non-leap years.
    • Deterministic tie-breaking: Whenever two events tie (same city, equal days from birthday, or equal geographic distance), break ties by earlier start_time, then smaller event.id.
    • Fewer than 5 matching events: Return all matching events (and if 0 upcoming events match, send zero notifications).
    • Notification formatting: One notification per selected event in [<label>] <title> - <YYYY-MM-DD HH:MM> - <event city> format, e.g. [Near you] Blues Jam - 2026-09-14 20:00 - Austin.

    Using @dataclass(frozen=True) makes Customer and Event immutable value objects so a campaign can never accidentally mutate the shared event list:

    from dataclasses import dataclass
    from datetime import date, datetime
    
    
    @dataclass(frozen=True)
    class Customer:
        id: int
        city: str
        birth_month: int
        birth_day: int
        latitude: float
        longitude: float
    
    
    @dataclass(frozen=True)
    class Event:
        id: int
        title: str
        city: str
        start_time: datetime
        latitude: float
        longitude: float
    
    
    class NotificationService:
        """Sends one message to one customer (push, e-mail, SMS...)."""
    
        def send(self, customer_id: int, message: str) -> None:
            raise NotImplementedError
    
  2. Decouple the engine from campaigns with the Strategy pattern

    If MarketingEngine had a giant if/elif block for city, birthday, and distance, adding a fourth campaign ("Weekend events" or "Favorite artist") would force us to edit and re-test MarketingEngine every time.

    Instead, we apply the Strategy pattern (encapsulating each selection rule behind a common interface so rules can be swapped or added freely):

      events + today
            |
            v
      +---------------------------+      1. select(customer, upcoming, today)
      |     MarketingEngine       | -----------------------------------------+
      | (filters upcoming once,   |                                          |
      |  orchestrates & sends)    | <----------------------------------------+
      +---------------------------+      2. format_message(customer, event)  |
            |                                                                v
            | 3. send(customer.id, msg)                       +-----------------------------+
            v                                                 |      Campaign (base)        |
      +---------------------------+                           +-----------------------------+
      |    NotificationService    |                              ^           ^           ^
      +---------------------------+                              |           |           |
                                                           SameCity      Birthday   NearestEvents
    

    Notice the clean separation of duties:

    • Campaigns never call NotificationService.send—they only decide which upcoming events apply (select) and how a single line reads (format_message).
    • MarketingEngine knows nothing about cities, birthdays, or coordinates—it filters upcoming events once, loops through the injected Campaign list, and dispatches through NotificationService.
    from typing import List
    
    
    class Campaign:
        """One marketing rule. Subclass it and pass the instance to MarketingEngine."""
    
        label = "Campaign"
    
        def select(self, customer: Customer, events: List[Event], today: date) -> List[Event]:
            """Events to notify about, in message order. events are all upcoming."""
            raise NotImplementedError
    
        def format_message(self, customer: Customer, event: Event) -> str:
            """'[<label>] <title> - <start as YYYY-MM-DD HH:MM> - <event city>'."""
            return f"[{self.label}] {event.title} - {event.start_time:%Y-%m-%d %H:%M} - {event.city}"
    
  3. Handle upcoming dates, year rollovers, and Feb 29 birthdays

    Computing next_birthday directly with date(today.year, birth_month, birth_day) has two classic calendar traps:

    1. Year rollover and birthday-today: On 2026-12-20, a Jan 5 birthday (2026-01-05) and a Dec 20 birthday (2026-12-20) both satisfy candidate <= today, so we must advance to today.year + 1 (2027).
    2. Leap-day birthdays (Feb 29): Calling date(2027, 2, 29) crashes with ValueError: day is out of range for month because 2027 is not a leap year! Putting the Feb 29 -> Feb 28 rule inside _birthday_in_year protects both today.year and today.year + 1.
    Examples for next_birthday(month, day, today):
      birth = Jan 5,  today = 2026-12-20  -> 2026-01-05 <= today -> rolls to 2027-01-05
      birth = Dec 20, today = 2026-12-20  -> 2026-12-20 <= today -> rolls to 2027-12-20 (strictly after!)
      birth = Feb 29, today = 2027-02-28  -> 2027-02-28 <= today -> rolls to 2028-02-29 (2028 is leap!)
    
    import calendar
    
    
    def is_upcoming(event: Event, today: date) -> bool:
        """An event is upcoming if it starts today or later."""
        # Compare calendar dates (>=) because `today` has no time-of-day component.
        return event.start_time.date() >= today
    
    
    def _birthday_in_year(birth_month: int, birth_day: int, year: int) -> date:
        """Calendar date on which a birthday is observed in `year`."""
        # date(year, 2, 29) raises ValueError in non-leap years; map Feb 29 to Feb 28 instead.
        if birth_month == 2 and birth_day == 29 and not calendar.isleap(year):
            return date(year, 2, 28)
        return date(year, birth_month, birth_day)
    
    
    def next_birthday(birth_month: int, birth_day: int, today: date) -> date:
        """First birthday strictly after today."""
        candidate = _birthday_in_year(birth_month, birth_day, today.year)
        # Use "<=" because "after today" is strict: if today IS the birthday, advance to next year.
        if candidate <= today:
            candidate = _birthday_in_year(birth_month, birth_day, today.year + 1)
        return candidate
    
  4. Campaign 1: Upcoming events in the customer's city

    Real user profiles contain "Seattle", "SEATTLE", and " seattle ", so _same_city strips whitespace and calls .casefold() before comparing.

    Look closely at how we sort matching events: we store (event.start_time, event.id, position) rather than (event.start_time, event.id, event). Why? Because Event is @dataclass(frozen=True) without order=True—if two Event objects ever shared the same start_time and id, Python would try to compare the Event instances themselves and crash with TypeError: '<' not supported between instances of 'Event' and 'Event'. Using the unique integer position guarantees tuple comparison never fails.

    from typing import Tuple
    
    
    def _same_city(city_a: str, city_b: str) -> bool:
        """Case-insensitive city comparison ignoring leading/trailing whitespace."""
        return city_a.strip().casefold() == city_b.strip().casefold()
    
    
    class SameCityCampaign(Campaign):
        """Every upcoming event in the customer's city, earliest first."""
    
        label = "In your city"
    
        def select(self, customer: Customer, events: List[Event], today: date) -> List[Event]:
            # ranked: list of (start_time, event_id, original_index), e.g. [(datetime(...), 2, 1)].
            # Storing original_index instead of Event avoids TypeError because Event is not orderable.
            ranked: List[Tuple[datetime, int, int]] = []
            for position, event in enumerate(events):
                if _same_city(event.city, customer.city):
                    ranked.append((event.start_time, event.id, position))
    
            ranked.sort()
            result: List[Event] = []
            for _, _, position in ranked:
                result.append(events[position])
            return result
    
  5. Campaign 2: Single event closest to the next birthday

    An upcoming event can fall before or after the customer's next birthday—for example, on today = 2026-12-20 with next birthday 2027-01-03, a New Year's Eve concert on 2026-12-31 (3 days before) is closer than a show on 2027-01-10 (7 days after):

      today             Event 10          Next Birthday            Event 11
    2026-12-20         2026-12-31          2027-01-03             2027-01-10
        |------------------|---- 3 days ------>|<------ 7 days --------|
    

    Using abs((event.start_time.date() - birthday).days) measures distance symmetrically on both sides, and comparing tuple keys (days_away, event.start_time, event.id) finds the winner in a single O(n) pass with automatic tie-breaking (so 2 days before beats 2 days after, and 18:00 on the birthday beats 21:00 on the birthday):

    class BirthdayCampaign(Campaign):
        """The single upcoming event whose date is closest to the next birthday."""
    
        label = "For your birthday"
    
        def select(self, customer: Customer, events: List[Event], today: date) -> List[Event]:
            birthday = next_birthday(customer.birth_month, customer.birth_day, today)
            best_event = None
            # best_key: (days_away, start_time, event_id) so ties break by earlier start_time, then smaller id.
            best_key = None
    
            for event in events:
                # abs(...) measures proximity on EITHER side of the birthday (e.g. 2 days before == 2 days after).
                days_away = abs((event.start_time.date() - birthday).days)
                key = (days_away, event.start_time, event.id)
                if best_key is None or key < best_key:
                    best_event = event
                    best_key = key
    
            if best_event is None:
                return []
            return [best_event]
    
  6. Campaign 3: Top k nearest events by Euclidean distance

    The prompt permits Euclidean distance on (latitude, longitude): sqrt((lat2 - lat1)^2 + (lon2 - lon1)^2), computed accurately by math.hypot(delta_lat, delta_lon).

    Instead of sorting all n events (O(n log n)), heapq.nsmallest(self.limit, ranked) maintains a small heap of size at most limit (default 5), running in O(n log limit) time and returning results sorted from nearest to farthest. Better yet, when fewer than 5 upcoming events exist, heapq.nsmallest returns all of them automatically without extra if len(events) < 5 branches!

    import heapq
    import math
    
    
    def _distance(customer: Customer, event: Event) -> float:
        """Euclidean distance on (latitude, longitude), as the statement allows."""
        delta_lat = event.latitude - customer.latitude
        delta_lon = event.longitude - customer.longitude
        return math.hypot(delta_lat, delta_lon)
    
    
    class NearestEventsCampaign(Campaign):
        """Up to `limit` upcoming events closest to the customer, nearest first."""
    
        label = "Near you"
    
        def __init__(self, limit: int = 5) -> None:
            if limit < 1:
                raise ValueError("limit must be at least 1")
            self.limit = limit
    
        def select(self, customer: Customer, events: List[Event], today: date) -> List[Event]:
            # ranked: list of (euclidean_dist, start_time, event_id, original_index) tuples.
            # Ties on distance break automatically by earlier start_time, then smaller event_id.
            ranked: List[Tuple[float, datetime, int, int]] = []
            for position, event in enumerate(events):
                dist = _distance(customer, event)
                ranked.append((dist, event.start_time, event.id, position))
    
            # heapq.nsmallest runs in O(n log limit) and returns all items when len(ranked) < limit.
            closest = heapq.nsmallest(self.limit, ranked)
            result: List[Event] = []
            for _, _, _, position in closest:
                result.append(events[position])
            return result
    
  7. Assemble MarketingEngine

    MarketingEngine takes notifier and campaigns via its constructor (dependency injection—passing collaborators in from outside rather than instantiating them internally, which makes unit testing with a fake RecordingNotifier effortless). send_customer_notifications filters upcoming events once, runs each campaign in order, sends formatted messages, and returns the sent strings:

    from typing import Sequence
    
    
    class MarketingEngine:
        """Runs every campaign for a customer and sends one message per selected event."""
    
        def __init__(self, notifier: NotificationService, campaigns: Sequence[Campaign]) -> None:
            # Inject both notifier and campaigns so tests can pass fakes and new rules need zero engine edits.
            self._notifier = notifier
            self._campaigns = list(campaigns)
    
        def send_customer_notifications(self, customer: Customer, events: List[Event], today: date) -> List[str]:
            """Send the messages in campaign order and return them."""
            # Filter upcoming events once up front so no Campaign subclass can accidentally leak past events.
            upcoming: List[Event] = []
            for event in events:
                if is_upcoming(event, today):
                    upcoming.append(event)
    
            sent: List[str] = []
            for campaign in self._campaigns:
                selected_events = campaign.select(customer, upcoming, today)
                for event in selected_events:
                    message = campaign.format_message(customer, event)
                    self._notifier.send(customer.id, message)
                    sent.append(message)
            return sent
    
  8. Trace Example 1 across all three campaigns

    Consider Example 1: Customer 88 lives in "Austin" at (0.0, 0.0) with birthday September 25, and today = 2026-09-10:

    Event | Title          | City   | Start Time       | (lat, lon) | Upcoming?  | Dist from (0,0) | Days from 2026-09-25
    ------+----------------+--------+------------------+------------+------------+-----------------+---------------------
    10    | Blues Jam      | Austin | 2026-09-14 20:00 | (1.0, 1.0) | Yes        | sqrt(2) = 1.414 | |09-14 - 09-25| = 11
    20    | Indie Showcase | Dallas | 2026-09-24 19:30 | (0.0, 4.0) | Yes        | sqrt(16) = 4.00 | |09-24 - 09-25| = 1
    30    | Summer Finale  | Austin | 2026-09-01 18:00 | (0.0, 0.0) | No (<09-10)| (dropped first!)| (dropped first!)
    

    Running [SameCityCampaign(), BirthdayCampaign(), NearestEventsCampaign(limit=5)] emits 4 notifications in order:

    1. SameCityCampaign -> Event 10 ("Austin" matches; Event 30 was already dropped): [In your city] Blues Jam - 2026-09-14 20:00 - Austin
    2. BirthdayCampaign -> Event 20 (1 day from 2026-09-25 beats 11 days): [For your birthday] Indie Showcase - 2026-09-24 19:30 - Dallas
    3. NearestEventsCampaign(limit=5) -> only 2 upcoming events exist (< 5), sorted 1.414 < 4.00: [Near you] Blues Jam - 2026-09-14 20:00 - Austin [Near you] Indie Showcase - 2026-09-24 19:30 - Dallas
  9. Complete solution

    from typing import List, Sequence, Tuple
    from dataclasses import dataclass
    from datetime import date, datetime
    import calendar
    import heapq
    import math
    
    
    @dataclass(frozen=True)
    class Customer:
        id: int
        city: str
        birth_month: int
        birth_day: int
        latitude: float
        longitude: float
    
    
    @dataclass(frozen=True)
    class Event:
        id: int
        title: str
        city: str
        start_time: datetime
        latitude: float
        longitude: float
    
    
    class NotificationService:
        """Sends one message to one customer (push, e-mail, SMS...)."""
    
        def send(self, customer_id: int, message: str) -> None:
            raise NotImplementedError
    
    
    def is_upcoming(event: Event, today: date) -> bool:
        """An event is upcoming if it starts today or later."""
        # Compare calendar dates (>=) because `today` has no time-of-day component.
        return event.start_time.date() >= today
    
    
    def _birthday_in_year(birth_month: int, birth_day: int, year: int) -> date:
        """Calendar date on which a birthday is observed in `year`."""
        # date(year, 2, 29) raises ValueError in non-leap years; map Feb 29 to Feb 28 instead.
        if birth_month == 2 and birth_day == 29 and not calendar.isleap(year):
            return date(year, 2, 28)
        return date(year, birth_month, birth_day)
    
    
    def next_birthday(birth_month: int, birth_day: int, today: date) -> date:
        """First birthday strictly after today."""
        candidate = _birthday_in_year(birth_month, birth_day, today.year)
        # Use "<=" because "after today" is strict: if today IS the birthday, advance to next year.
        if candidate <= today:
            candidate = _birthday_in_year(birth_month, birth_day, today.year + 1)
        return candidate
    
    
    def _same_city(city_a: str, city_b: str) -> bool:
        """Case-insensitive city comparison ignoring leading/trailing whitespace."""
        return city_a.strip().casefold() == city_b.strip().casefold()
    
    
    def _distance(customer: Customer, event: Event) -> float:
        """Euclidean distance on (latitude, longitude), as the statement allows."""
        delta_lat = event.latitude - customer.latitude
        delta_lon = event.longitude - customer.longitude
        return math.hypot(delta_lat, delta_lon)
    
    
    class Campaign:
        """One marketing rule. Subclass it and pass the instance to MarketingEngine."""
    
        label = "Campaign"
    
        def select(self, customer: Customer, events: List[Event], today: date) -> List[Event]:
            """Events to notify about, in message order. events are all upcoming."""
            raise NotImplementedError
    
        def format_message(self, customer: Customer, event: Event) -> str:
            """'[<label>] <title> - <start as YYYY-MM-DD HH:MM> - <event city>'."""
            return f"[{self.label}] {event.title} - {event.start_time:%Y-%m-%d %H:%M} - {event.city}"
    
    
    class SameCityCampaign(Campaign):
        """Every upcoming event in the customer's city, earliest first."""
    
        label = "In your city"
    
        def select(self, customer: Customer, events: List[Event], today: date) -> List[Event]:
            # ranked: list of (start_time, event_id, original_index), e.g. [(datetime(...), 2, 1)].
            # Storing original_index instead of Event avoids TypeError because Event is not orderable.
            ranked: List[Tuple[datetime, int, int]] = []
            for position, event in enumerate(events):
                if _same_city(event.city, customer.city):
                    ranked.append((event.start_time, event.id, position))
    
            ranked.sort()
            result: List[Event] = []
            for _, _, position in ranked:
                result.append(events[position])
            return result
    
    
    class BirthdayCampaign(Campaign):
        """The single upcoming event whose date is closest to the next birthday."""
    
        label = "For your birthday"
    
        def select(self, customer: Customer, events: List[Event], today: date) -> List[Event]:
            birthday = next_birthday(customer.birth_month, customer.birth_day, today)
            best_event = None
            # best_key: (days_away, start_time, event_id) so ties break by earlier start_time, then smaller id.
            best_key = None
    
            for event in events:
                # abs(...) measures proximity on EITHER side of the birthday (e.g. 2 days before == 2 days after).
                days_away = abs((event.start_time.date() - birthday).days)
                key = (days_away, event.start_time, event.id)
                if best_key is None or key < best_key:
                    best_event = event
                    best_key = key
    
            if best_event is None:
                return []
            return [best_event]
    
    
    class NearestEventsCampaign(Campaign):
        """Up to `limit` upcoming events closest to the customer, nearest first."""
    
        label = "Near you"
    
        def __init__(self, limit: int = 5) -> None:
            if limit < 1:
                raise ValueError("limit must be at least 1")
            self.limit = limit
    
        def select(self, customer: Customer, events: List[Event], today: date) -> List[Event]:
            # ranked: list of (euclidean_dist, start_time, event_id, original_index) tuples.
            # Ties on distance break automatically by earlier start_time, then smaller event_id.
            ranked: List[Tuple[float, datetime, int, int]] = []
            for position, event in enumerate(events):
                dist = _distance(customer, event)
                ranked.append((dist, event.start_time, event.id, position))
    
            # heapq.nsmallest runs in O(n log limit) and returns all items when len(ranked) < limit.
            closest = heapq.nsmallest(self.limit, ranked)
            result: List[Event] = []
            for _, _, _, position in closest:
                result.append(events[position])
            return result
    
    
    class MarketingEngine:
        """Runs every campaign for a customer and sends one message per selected event."""
    
        def __init__(self, notifier: NotificationService, campaigns: Sequence[Campaign]) -> None:
            # Inject both notifier and campaigns so tests can pass fakes and new rules need zero engine edits.
            self._notifier = notifier
            self._campaigns = list(campaigns)
    
        def send_customer_notifications(self, customer: Customer, events: List[Event], today: date) -> List[str]:
            """Send the messages in campaign order and return them."""
            # Filter upcoming events once up front so no Campaign subclass can accidentally leak past events.
            upcoming: List[Event] = []
            for event in events:
                if is_upcoming(event, today):
                    upcoming.append(event)
    
            sent: List[str] = []
            for campaign in self._campaigns:
                selected_events = campaign.select(customer, upcoming, today)
                for event in selected_events:
                    message = campaign.format_message(customer, event)
                    self._notifier.send(customer.id, message)
                    sent.append(message)
            return sent
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Think of MarketingEngine like a newspaper printing press that accepts interchangeable printing plates (Campaign objects). The press itself knows nothing about cities, birthdays, or map coordinates—it simply filters out yesterday's expired events once, asks each plugged-in Campaign plate which upcoming events it wants and how to format its headline, and hands the finished strings to the mailroom (NotificationService). That structure is the Strategy pattern (putting each interchangeable rule in its own class behind one shared select / format_message interface), which satisfies the Open-Closed Principle (code is open for adding new campaigns without modifying the core engine).

Cramming all three rules into one big if/elif function inside MarketingEngine—or letting each campaign call NotificationService.send directly—creates immediate maintenance headaches. Every new marketing idea would force edits to the engine's core loop, unit testing a campaign would require mocking network delivery, and cross-campaign policies like filtering past events or capping daily messages would have to be copy-pasted into every rule.

Walk through the 3-event catalog of Example 1 on today = 2026-09-10 for Customer 88 in "Austin" at (0, 0) with birthday September 25:

  1. Pre-filter once: Summer Finale (2026-09-01, Austin) is dropped up front, leaving Blues Jam (2026-09-14, Austin, (1, 1)) and Indie Showcase (2026-09-24, Dallas, (0, 4)).
  2. SameCityCampaign: Matches Blues Jam ("Austin" == "Austin").
  3. BirthdayCampaign: Next birthday after 2026-09-10 is 2026-09-25; Indie Showcase is |09-24 - 09-25| = 1 day away versus 11 days for Blues Jam, so Indie Showcase wins.
  4. NearestEventsCampaign(limit=5): Computes Euclidean distance (sqrt((lat2 - lat1)^2 + (lon2 - lon1)^2)) giving 1.414 for Blues Jam and 4.0 for Indie Showcase, returning both in nearest-first order since fewer than 5 upcoming events exist.

Complexity

Let n be the total number of input events, m be the number of upcoming events in the customer's city (m <= n), and k be the nearest-events limit (k = 5 by default), for a single customer call:

  • Time:
    • Upcoming pre-filter: O(n) because we scan the n events once and compare event.start_time.date() >= today.
    • SameCityCampaign: O(n + m log m) because we check every upcoming event's city in O(n) and sort the m city matches by (start_time, id, position).
    • BirthdayCampaign: O(n) because we scan upcoming events once while tracking the minimum (days_away, start_time, id) tuple.
    • NearestEventsCampaign: O(n log k) because heapq.nsmallest—which maintains a min-heap (a compact binary tree that keeps its extreme element accessible in O(log k) per update) of size at most k—visits each of the n events once; for fixed k = 5, log k is constant, making this O(n).
    • Total per customer: O(n log n) in the worst case when almost all events are in the customer's city (m ≈ n), or O(n) when m is small.
  • Space: O(n) auxiliary memory to hold the upcoming list and the ranking tuples (..., position).

Edge cases

  • Events happening later (or earlier) on today: Included because event.start_time.date() >= today compares dates; pass a timezone-aware now: datetime instead if already-started shows today should be excluded.
  • Birthday falls on today: Because the specification asks for the next birthday after today, candidate <= today rolls 2026-09-25 forward to 2027-09-25. Changing <= to < is a one-character edit if product wants today's birthday to stay in the current year.
  • Leap-day birthdays (Feb 29): Calling date(2027, 2, 29) raises ValueError in non-leap years; _birthday_in_year maps Feb 29 to Feb 28 in non-leap years while preserving Feb 29 in leap years (2028).
  • December-to-January year rollover: On 2026-12-20, a Jan 3 birthday resolves to 2027-01-03, and abs((event_date - birthday).days) properly prefers 2026-12-31 (3 days before) over 2027-01-10 (7 days after).
  • Deterministic tie-breaking: Equal day distances or equal Euclidean distances break by earlier start_time, then smaller event.id, then input position so output never depends on hash randomization or dataclass comparison errors.
  • Fewer than 5 (or 0) upcoming events: NearestEventsCampaign returns all available upcoming events ([] when empty), and BirthdayCampaign returns [] when no upcoming events exist.
  • City formatting quirks and homonyms: .strip().casefold()—where case folding is Unicode's aggressive case-insensitive normalization—matches " denver " and "DENVER". Note that two distinct cities sharing a name (Portland, OR vs Portland, ME) require a city_id or (city, state) key in production.
  • Antimeridian (±180° longitude) and high-latitude distortion: Raw Euclidean distance on degrees treats 179.9° and -179.9° as 359.8° apart and stretches east-west degrees away from the equator (addressed via haversine in follow-ups).

Common mistakes

  • Hard-coding campaign logic inside MarketingEngine with if/elif branches, violating the requirement that new campaigns require zero engine changes.
  • Having each Campaign call notifier.send(...) directly, which duplicates sending logic and makes cross-campaign deduplication or rate-limiting impossible in the engine.
  • Checking only event_date >= birthday in BirthdayCampaign, missing an event 1 day before the birthday in favor of an event 20 days after it.
  • Constructing date(today.year, birth_month, birth_day) directly, crashing with ValueError for every Feb 29 customer in 3 out of every 4 years, or forgetting year rollover when candidate <= today.
  • Putting event as the last element of a sort/heap tuple (distance, event): if distances tie, Python compares two Event dataclasses and raises TypeError because @dataclass(frozen=True) does not define <.
  • Filtering upcoming events separately inside every campaign instead of once in MarketingEngine, risking a newly added campaign accidentally notifying users about last month's concerts.

Alternative approaches

  • Returning structured Notification data objects instead of formatted strings: Have campaigns emit Notification(campaign_id, customer_id, event_id, template_vars) and hand rendering to a channel-specific formatter (push vs email vs SMS, localized into the user's language).
  • Digest notifications (build_messages(customer, selected_events)): If a customer's city has 80 concerts next month, sending one digest ("5 upcoming shows in Austin: Blues Jam, ...") avoids spamming 80 push alerts. Adding a default build_messages method on Campaign supports both per-event alerts and multi-event digests without changing MarketingEngine.

Follow-up questions

  • How would you suppress duplicate alerts when multiple campaigns pick the same event, or enforce a per-customer daily message cap? Centralize both rules in MarketingEngine.send_customer_notifications, since the engine sees every campaign's selections before calling notifier.send. Track an already_announced: Set[int] of event.ids within the loop (so ordering campaigns from highest to lowest priority suppresses duplicates in later campaigns) and break once len(sent) == max_messages_per_run. Across separate worker retries, pass an idempotency key (a deterministic token like f"{customer.id}:{campaign.label}:{event.id}:{today}") to NotificationService so a retried batch job never double-texts the user.
  • How would you upgrade Euclidean coordinate distance to accurate Earth-surface distance? Compute haversine (great-circle) distance—the shortest path between two (latitude, longitude) points along a sphere of radius R ≈ 6371 km using spherical trigonometry: a = sin²(Δlat/2) + cos(lat1) * cos(lat2) * sin²(Δlon/2) and d = 2 * R * asin(sqrt(a)). Haversine automatically accounts for longitude lines converging near the poles (at 47.6° N, 1° of longitude is ~75 km while 1° of latitude is ~111 km) and wraps cleanly across ±180° longitude.
  • How would you scale campaign evaluation to 10 million customers and 100,000 upcoming events? Scanning 100,000 events for each of 10 million customers (10^12 pairs) is far too slow, so pre-build shared read-only indexes over upcoming events once at the start of the batch run:
    1. A dictionary city_key -> sorted_events turns SameCityCampaign into an O(1) lookup.
    2. Sorting upcoming events by start_time.date() lets BirthdayCampaign find the closest date on either side of birthday via binary search (bisect) in O(log n) time per customer.
    3. A spatial index (a data structure such as a k-d tree or geohash grid that buckets 2D/3D coordinates into nearby regions) lets NearestEventsCampaign query only neighboring map cells instead of the whole globe, while worker processes shard customers in parallel and enqueue outbound messages asynchronously.

Follow-up questions

Similar questions

More StubHub interview questions

All 9 StubHub questions →