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
is_upcoming(event: Event, today: date) -> bool:- Return
Trueif and only ifevent.start_time.date() >= today.
- Return
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 29birthday is observed onFeb 28in non-leap years andFeb 29in leap years.
- Return the earliest calendar date strictly after
Campaign(extensible strategy base class):- Class attribute
label = "Campaign". select(customer: Customer, events: List[Event], today: date) -> List[Event]: given upcomingevents, 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>".
- Class attribute
- Built-in
Campaignsubclasses:SameCityCampaign(label = "In your city"): select all upcoming events whosecitymatchescustomer.cityignoring 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 minimizingabs((event.start_time.date() - next_bday).days)on either side ofnext_birthday(...), breaking ties by earlierevent.start_time, then smallerevent.id. Return[]if no upcoming events exist.NearestEventsCampaign(limit: int = 5)(label = "Near you"): raiseValueErroriflimit < 1. Select up tolimitupcoming events closest to(customer.latitude, customer.longitude)under Euclidean distancehypot(d_lat, d_lon), ordered nearest first with ties broken by earlierevent.start_time, then smallerevent.id(return all upcoming events if fewer thanlimitexist).
MarketingEngine(notifier: NotificationService, campaigns: Sequence[Campaign]):send_customer_notifications(customer: Customer, events: List[Event], today: date) -> List[str]:- Filter
eventsonce viais_upcoming(event, today). - Execute
campaignsin sequence without any campaign-specificif/elifbranches inside the engine, so customCampaignsubclasses work unmodified. - Format each selected event with
campaign.format_message(customer, event), callnotifier.send(customer.id, message), and return all sent message strings in dispatch order.
- Filter
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;
NearestEventsCampaignrequireslimit >= 1.
Step-by-step walkthrough
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
todayis a calendardate(no clock hour), an event is upcoming whenevent.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: "Aftertoday" is strict (>). Iftodayis 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 onFeb 28in 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 smallerevent.id. - Fewer than 5 matching events: Return all matching events (and if
0upcoming 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)makesCustomerandEventimmutable 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- Upcoming events: Because
Decouple the engine from campaigns with the Strategy pattern
If
MarketingEnginehad a giantif/elifblock for city, birthday, and distance, adding a fourth campaign ("Weekend events" or "Favorite artist") would force us to edit and re-testMarketingEngineevery 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 NearestEventsNotice 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). MarketingEngineknows nothing about cities, birthdays, or coordinates—it filtersupcomingevents once, loops through the injectedCampaignlist, and dispatches throughNotificationService.
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}"- Campaigns never call
Handle upcoming dates, year rollovers, and Feb 29 birthdays
Computing
next_birthdaydirectly withdate(today.year, birth_month, birth_day)has two classic calendar traps:- Year rollover and birthday-today: On
2026-12-20, aJan 5birthday (2026-01-05) and aDec 20birthday (2026-12-20) both satisfycandidate <= today, so we must advance totoday.year + 1(2027). - Leap-day birthdays (
Feb 29): Callingdate(2027, 2, 29)crashes withValueError: day is out of range for monthbecause2027is not a leap year! Putting theFeb 29 -> Feb 28rule inside_birthday_in_yearprotects bothtoday.yearandtoday.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- Year rollover and birthday-today: On
Campaign 1: Upcoming events in the customer's city
Real user profiles contain
"Seattle","SEATTLE", and" seattle ", so_same_citystrips 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? BecauseEventis@dataclass(frozen=True)withoutorder=True—if twoEventobjects ever shared the samestart_timeandid, Python would try to compare theEventinstances themselves and crash withTypeError: '<' not supported between instances of 'Event' and 'Event'. Using the unique integerpositionguarantees 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 resultCampaign 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-20with next birthday2027-01-03, a New Year's Eve concert on2026-12-31(3days before) is closer than a show on2027-01-10(7days 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 singleO(n)pass with automatic tie-breaking (so2days before beats2days after, and18:00on the birthday beats21:00on 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]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 bymath.hypot(delta_lat, delta_lon).Instead of sorting all
nevents (O(n log n)),heapq.nsmallest(self.limit, ranked)maintains a small heap of size at mostlimit(default5), running inO(n log limit)time and returning results sorted from nearest to farthest. Better yet, when fewer than5upcoming events exist,heapq.nsmallestreturns all of them automatically without extraif len(events) < 5branches!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 resultAssemble MarketingEngine
MarketingEnginetakesnotifierandcampaignsvia its constructor (dependency injection—passing collaborators in from outside rather than instantiating them internally, which makes unit testing with a fakeRecordingNotifiereffortless).send_customer_notificationsfiltersupcomingevents 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 sentTrace Example 1 across all three campaigns
Consider Example 1: Customer
88lives in"Austin"at(0.0, 0.0)with birthdaySeptember 25, andtoday = 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:SameCityCampaign-> Event 10 ("Austin"matches; Event 30 was already dropped):[In your city] Blues Jam - 2026-09-14 20:00 - AustinBirthdayCampaign-> Event 20 (1day from2026-09-25beats11days):[For your birthday] Indie Showcase - 2026-09-24 19:30 - DallasNearestEventsCampaign(limit=5)-> only 2 upcoming events exist (< 5), sorted1.414 < 4.00:[Near you] Blues Jam - 2026-09-14 20:00 - Austin[Near you] Indie Showcase - 2026-09-24 19:30 - Dallas
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:
- Pre-filter once:
Summer Finale(2026-09-01, Austin) is dropped up front, leavingBlues Jam(2026-09-14, Austin,(1, 1)) andIndie Showcase(2026-09-24, Dallas,(0, 4)). SameCityCampaign: MatchesBlues Jam("Austin" == "Austin").BirthdayCampaign: Next birthday after2026-09-10is2026-09-25;Indie Showcaseis|09-24 - 09-25| = 1day away versus11days forBlues Jam, soIndie Showcasewins.NearestEventsCampaign(limit=5): Computes Euclidean distance (sqrt((lat2 - lat1)^2 + (lon2 - lon1)^2)) giving1.414forBlues Jamand4.0forIndie 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 thenevents once and compareevent.start_time.date() >= today. SameCityCampaign:O(n + m log m)because we check every upcoming event's city inO(n)and sort themcity 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)becauseheapq.nsmallest—which maintains a min-heap (a compact binary tree that keeps its extreme element accessible inO(log k)per update) of size at mostk—visits each of thenevents once; for fixedk = 5,log kis constant, making thisO(n).- Total per customer:
O(n log n)in the worst case when almost all events are in the customer's city (m ≈ n), orO(n)whenmis small.
- Upcoming pre-filter:
- Space:
O(n)auxiliary memory to hold theupcominglist and the ranking tuples(..., position).
Edge cases
- Events happening later (or earlier) on
today: Included becauseevent.start_time.date() >= todaycompares dates; pass a timezone-awarenow: datetimeinstead if already-started shows today should be excluded. - Birthday falls on
today: Because the specification asks for the next birthday aftertoday,candidate <= todayrolls2026-09-25forward to2027-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): Callingdate(2027, 2, 29)raisesValueErrorin non-leap years;_birthday_in_yearmapsFeb 29toFeb 28in non-leap years while preservingFeb 29in leap years (2028). - December-to-January year rollover: On
2026-12-20, aJan 3birthday resolves to2027-01-03, andabs((event_date - birthday).days)properly prefers2026-12-31(3days before) over2027-01-10(7days after). - Deterministic tie-breaking: Equal day distances or equal Euclidean distances break by earlier
start_time, then smallerevent.id, then inputpositionso output never depends on hash randomization or dataclass comparison errors. - Fewer than
5(or0) upcoming events:NearestEventsCampaignreturns all available upcoming events ([]when empty), andBirthdayCampaignreturns[]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 acity_idor(city, state)key in production. - Antimeridian (
±180°longitude) and high-latitude distortion: Raw Euclidean distance on degrees treats179.9°and-179.9°as359.8°apart and stretches east-west degrees away from the equator (addressed via haversine in follow-ups).
Common mistakes
- Hard-coding campaign logic inside
MarketingEnginewithif/elifbranches, violating the requirement that new campaigns require zero engine changes. - Having each
Campaigncallnotifier.send(...)directly, which duplicates sending logic and makes cross-campaign deduplication or rate-limiting impossible in the engine. - Checking only
event_date >= birthdayinBirthdayCampaign, missing an event1day before the birthday in favor of an event20days after it. - Constructing
date(today.year, birth_month, birth_day)directly, crashing withValueErrorfor everyFeb 29customer in 3 out of every 4 years, or forgetting year rollover whencandidate <= today. - Putting
eventas the last element of a sort/heap tuple(distance, event): if distances tie, Python compares twoEventdataclasses and raisesTypeErrorbecause@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
Notificationdata objects instead of formatted strings: Have campaigns emitNotification(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 defaultbuild_messagesmethod onCampaignsupports both per-event alerts and multi-event digests without changingMarketingEngine.
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 callingnotifier.send. Track analready_announced: Set[int]ofevent.ids within the loop (so orderingcampaignsfrom highest to lowest priority suppresses duplicates in later campaigns) and break oncelen(sent) == max_messages_per_run. Across separate worker retries, pass an idempotency key (a deterministic token likef"{customer.id}:{campaign.label}:{event.id}:{today}") toNotificationServiceso 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 radiusR ≈ 6371 kmusing spherical trigonometry:a = sin²(Δlat/2) + cos(lat1) * cos(lat2) * sin²(Δlon/2)andd = 2 * R * asin(sqrt(a)). Haversine automatically accounts for longitude lines converging near the poles (at47.6° N,1°of longitude is ~75 kmwhile1°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^12pairs) is far too slow, so pre-build shared read-only indexes overupcomingevents once at the start of the batch run:- A dictionary
city_key -> sorted_eventsturnsSameCityCampaigninto anO(1)lookup. - Sorting upcoming events by
start_time.date()letsBirthdayCampaignfind the closest date on either side ofbirthdayvia binary search (bisect) inO(log n)time per customer. - A spatial index (a data structure such as a k-d tree or geohash grid that buckets 2D/3D coordinates into nearby regions) lets
NearestEventsCampaignquery only neighboring map cells instead of the whole globe, while worker processes shard customers in parallel and enqueue outbound messages asynchronously.
- A dictionary
Follow-up questions
- How would you suppress duplicate alerts when multiple campaigns pick the same event, or enforce a per-customer daily message cap?
- How would you upgrade Euclidean coordinate distance to accurate Earth-surface distance?
- How would you scale campaign evaluation to 10 million customers and 100,000 upcoming events?
Similar questions
- Composable Event Filtering and Ranking Engine
- Tiered Event Recommendation Engine with Fallbacks
- Worldwide Promotional Email Service Architecture
- Strategy-Based Event Recommender
- Scalable Event Notification Email Platform
- Real-Time Workforce Chat and 10-Day Customer Win-Back System
More StubHub interview questions
- Deep-Dive Walkthrough of a Shipped Engineering Project Medium
- Scalable Event Notification Email Platform Medium
- Real-Time Workforce Chat and 10-Day Customer Win-Back System Medium Pro
- Strategy-Based Event Recommender Medium Pro
- Composable Event Filtering and Ranking Engine Medium Pro
- Worldwide Promotional Email Service Architecture Medium Pro
- Tiered Event Recommendation Engine with Fallbacks Medium Pro
- Auditing and Hardening the getEvents Endpoint Hard Pro