Event-Driven Subscription Notification Scheduler
Medium · Coding & Algorithms · Software Engineer · Technical Screen
Problem Statement
Build an event-driven notification scheduler for customer subscriptions by implementing:
def send_emails(
user_accounts: List[dict],
send_schedule: Dict,
changes: Optional[List[dict]] = None,
) -> List[str]:
Each entry in user_accounts is a dictionary {"name": str, "plan": str, "account_date": int, "duration": int} representing one subscriber who signs up on integer day account_date with an initial term of duration days, giving an initial expiration day of end_date = account_date + duration.
The send_schedule dictionary maps trigger keys to message labels (every key is optional, and non-integer keys other than "start" and "end"—including bool keys—are ignored):
"start": label emitted onaccount_date.- Integer day offset
k(for instance,-7): label emitted on dayend_date + k. Any offset notification that would fall strictly beforeaccount_dateis suppressed. "end": label emitted onend_date.
The optional changes parameter (None or a list of dictionaries) supplies live account updates, where each dictionary targets an existing "name" on "change_date" (int) and takes one of two shapes:
- Tier switch
{"name": str, "new_plan": str, "change_date": int}: emits a"Changed"notification atchange_dateand switches the subscriber's active plan tonew_planimmediately. The"Changed"line itself, any lower-priority events sharingchange_date, and all future notifications for that subscriber must reflectnew_plan. - Term extension
{"name": str, "extension": int, "change_date": int}: emits a"Renewed"notification atchange_dateusing the subscriber's current active plan and increasesend_datebyextensiondays (end_date += extension, measured from the currentend_dateeven whenchange_date > end_date). Every unsent integer-offset reminder and"end"message from the previousend_date(including ones scheduled atchange_date) is cancelled, and replacement offset and"end"messages are scheduled for the updatedend_date. Any replacement event whose timestamp lands strictly beforechange_date(or strictly beforeaccount_datefor offsets) is skipped.
Format each emitted notification as:
<time>: [<Label>] Subscription for <name> (<plan>)
Return all emitted lines in ascending timestamp order. Whenever multiple events fall on the exact same day, break ties using this priority order:
"Changed"events"Renewed"events"start"events- Integer-offset events, ordered by numeric offset
kfrom smallest (most negative) to largest "end"events
Within the same priority bucket (and identical numeric offset k), order lines alphabetically by "name". If two state-change entries for the same subscriber still tie on day and bucket, keep their appearance order in changes.
Examples
Example 1
Input:
send_schedule = {"start": "Activated", -7: "7d Notice", "end": "Ended"}
user_accounts = [
{"name": "Clara", "plan": "Silver", "account_date": 2, "duration": 20},
{"name": "Devon", "plan": "Gold", "account_date": 5, "duration": 7},
]
changes = None
Output:
[
"2: [Activated] Subscription for Clara (Silver)",
"5: [Activated] Subscription for Devon (Gold)",
"5: [7d Notice] Subscription for Devon (Gold)",
"12: [Ended] Subscription for Devon (Gold)",
"15: [7d Notice] Subscription for Clara (Silver)",
"22: [Ended] Subscription for Clara (Silver)",
]
Explanation: Clara spans days 2..22 (with her -7 reminder at day 15), while Devon spans days 5..12 (so his -7 reminder lands on day 5). On day 5, Devon's "start" notification precedes his -7 offset notification by bucket priority.
Example 2
Input:
send_schedule = {"start": "Activated", -7: "7d Notice", "end": "Ended"}
user_accounts = [
{"name": "Clara", "plan": "Silver", "account_date": 2, "duration": 20},
{"name": "Devon", "plan": "Gold", "account_date": 5, "duration": 7},
]
changes = [
{"name": "Clara", "extension": 14, "change_date": 10},
{"name": "Devon", "extension": 5, "change_date": 12},
{"name": "Devon", "new_plan": "Platinum", "change_date": 12},
]
Output:
[
"2: [Activated] Subscription for Clara (Silver)",
"5: [Activated] Subscription for Devon (Gold)",
"5: [7d Notice] Subscription for Devon (Gold)",
"10: [Renewed] Subscription for Clara (Silver)",
"12: [Changed] Subscription for Devon (Platinum)",
"12: [Renewed] Subscription for Devon (Platinum)",
"17: [Ended] Subscription for Devon (Platinum)",
"29: [7d Notice] Subscription for Clara (Silver)",
"36: [Ended] Subscription for Clara (Silver)",
]
Explanation: On day 10, Clara extends her end day from 22 to 36, cancelling her old day-15 and day-22 emails and scheduling new ones at days 29 and 36. On day 12, Devon's "Changed" event runs before "Renewed" even though it appears later in changes, so "Renewed" already shows (Platinum). Extending Devon's end day from 12 to 17 suppresses his day-12 "Ended" message; the recomputed -7 reminder (17 - 7 = 10) falls before change_date = 12, so it is skipped.
Example 3
Input:
send_schedule = {-10: "10d Left", -3: "3d Left"}
user_accounts = [
{"name": "Maya", "plan": "Starter", "account_date": 0, "duration": 19},
{"name": "Leo", "plan": "Starter", "account_date": 4, "duration": 8},
]
changes = []
Output:
[
"9: [10d Left] Subscription for Maya (Starter)",
"9: [3d Left] Subscription for Leo (Starter)",
"16: [3d Left] Subscription for Maya (Starter)",
]
Explanation: "start" and "end" are omitted from send_schedule. Leo expires on day 12, so his -10 reminder (12 - 10 = 2) falls before account_date = 4 and is dropped. At day 9, Maya's -10 offset precedes Leo's -3 offset because -10 < -3 is compared before subscriber names.
Constraints
- Avoid day-by-day calendar iteration so multi-year durations run in time proportional to the number of scheduled and state-change events,
O(E log E). - Account names in
user_accountsmust be unique,duration >= 0, everychangesitem must reference a known"name"and specify either"new_plan"or"extension"(never both or neither), andextension >= 0. RaiseValueErrorwhenever any of these preconditions is violated.
Step-by-step walkthrough
Understand the timeline and tie-breaking rules
Each subscription account starts on
account_dateand initially expires onend_date = account_date + duration. Along that timeline,send_scheduleasks us to emit up to three kinds of scheduled emails per account:"start": sent onaccount_date.- Integer offsets (such as
-7): sent atend_date + offset(for example, 7 days before expiration). "end": sent onend_date.
On top of those baseline emails,
changesinjects live state updates: plan switches (new_plan) and renewals (extensiondays added to the currentend_date). Everything merges into a single chronological list of formatted strings:"<time>: [<Label>] Subscription for <name> (<plan>)".Clara: begin = 2, duration = 20 -> end = 22, offset -7 -> reminder at 15 Devon: begin = 5, duration = 7 -> end = 12, offset -7 -> reminder at 5 Day: 2 5 12 15 22 | | | | | Clara Devon [Activated] Devon Clara Clara [Activated] Devon [7d Notice] [Ended] [7d Notice] [Ended]Before writing code, we must pin down the subtle edge rules:
- Optional keys: any key in
send_schedule("start","end", or integer offsets) may be omitted. - No reminders before signup: if
end_date + offset < account_date(for instance, a-10day reminder on an 8-day subscription), we skip that reminder rather than warning a user before they even join. - Renewals cancel old end-relative emails: a renewal at timestamp
tshiftsend_dateforward byextensiondays from the currentend_date(even if the account already expired beforet). Any not-yet-sent reminders or"end"email tied to the oldend_dateare cancelled—including ones scheduled attitself, becauseRenewedruns before reminders and expirations att. Recomputed notifications that would land strictly beforetare skipped because timethas already arrived. - Input validation: duplicate account names, negative durations, unknown account names in
changes, negative extensions, or change dicts with neither/both ofnew_planandextensionraiseValueError. - Exact ties: if two changes for the same account share the exact same timestamp and bucket (such as two renewals on the same day), we preserve their input order.
Why walking the calendar day by day is too slow
A straightforward brute-force approach finds the earliest and latest day across the whole dataset and loops
for day in range(first_day, last_day + 1):. On each day, it applies plan changes, applies renewals, and scans allNaccounts to see whose start, offset, or end date equalsday.That day-by-day simulation is easy to reason about, so it makes a great test oracle, but its runtime depends on the calendar span
T(O(T * (N * K + M))). If a single enterprise customer buys a 10-year (3,650-day) plan, a day-by-day loop spins through thousands of empty days just to output three lines. Instead, we want an event-driven design that jumps directly from one active timestamp to the next.Encode tie-breaking inside a min-heap key
If there were no renewals, we could generate every notification up front, sort the list once, and format the strings. Because a renewal dynamically creates new future notifications while we walk through time, we use a min-heap (Python's
heapq), which always pops the earliest event inO(log E)time and lets us push newly scheduled events on the fly.All five tie-breaking rules fit directly into a single tuple key, which Python compares left to right:
Heap entry: (time, bucket, offset, name, seq, payload) | | | | | +-- extra data (dict, version int, or None) | | | | +--------- unique insertion counter (0, 1, 2, ...) | | | +--------------- account name ("Clara" < "Devon") | | +---------------------- numeric offset (-10 < -3; 0 for non-offsets) | +------------------------------ 0=CHANGED, 1=RENEWED, 2=START, 3=OFFSET, 4=END +------------------------------------- integer timestampTwo details in this tuple prevent subtle bugs:
offsetstores the raw negative integer (-10 < -3), so more-negative reminders automatically pop before less-negative ones without string-comparison bugs ("-10"vs"-3").seqis a strictly increasing counter (0, 1, 2, ...). Because two entries never share the sameseq, exact ties stay in input order AND Python never compares thepayloadfield at index 5 (comparing twodictpayloads in Python raisesTypeError).
import heapq # Priority buckets for events sharing the same timestamp; smaller integer pops first. # Order required by the spec: Changed -> Renewed -> start -> offsets -> end. CHANGED = 0 RENEWED = 1 START = 2 OFFSET = 3 END = 4 class EventQueue: """Min-heap of scheduled events ordered deterministically by tie-breaking rules.""" def __init__(self): # heap: min-heap of (time, bucket, offset, name, seq, payload) tuples. self.heap = [] # Monotonically increasing tie-breaker preserving input order for identical keys. self.next_seq = 0 def push(self, time: int, bucket: int, offset: int, name: str, payload) -> None: # Including `self.next_seq` before `payload` guarantees Python never compares `payload` # dicts directly (which would raise TypeError when earlier tuple fields tie). entry = (time, bucket, offset, name, self.next_seq, payload) heapq.heappush(self.heap, entry) self.next_seq += 1 def pop(self): time, bucket, offset, name, _, payload = heapq.heappop(self.heap) return time, bucket, offset, name, payload def __len__(self) -> int: return len(self.heap)Part (a): model accounts and queue baseline notifications
Rather than baking an account's plan string into every queued event at the beginning, we store one mutable
Accountobject per user in a dictionaryaccounts[name]. Queued events carry onlyaccount.name, and we readaccount.planat the moment the event is popped and formatted.schedule_end_eventspushes all relative-offset reminders and the"end"event for an account's currentend_date. Accepting anot_beforecutoff lets us reuse the exact same helper both at initial setup (not_before = account.begin_date) and later on renewals (not_before = renewal_time). Notice we also excludeboolkeys when scanningsend_schedulefor integer offsets, because in Pythonboolis a subclass ofint(isinstance(True, int)isTrue).from typing import Dict, List class Account: """Mutable state of a single user's subscription as the timeline advances.""" def __init__(self, name: str, plan: str, begin_date: int, end_date: int): self.name = name self.plan = plan self.begin_date = begin_date self.end_date = end_date # Incremented on every renewal so older end-relative events in the heap become stale. self.version = 0 def load_accounts(user_accounts: List[dict]) -> Dict[str, Account]: """Validate raw account dicts and build a lookup table keyed by unique account name.""" # accounts: dict mapping account_name -> Account(name, plan, begin_date, end_date, version) accounts: Dict[str, Account] = {} for row in user_accounts: name = row["name"] if name in accounts: raise ValueError(f"duplicate account name {name!r}") duration = row["duration"] if duration < 0: raise ValueError(f"negative duration for {name!r}") begin_date = row["account_date"] end_date = begin_date + duration accounts[name] = Account(name, row["plan"], begin_date, end_date) return accounts def relative_offsets(send_schedule: Dict) -> List[int]: """Extract integer day offsets from send_schedule sorted from most negative to least.""" offsets: List[int] = [] for key in send_schedule: # Exclude bool because bool is a subclass of int in Python (True == 1, False == 0). if isinstance(key, int) and not isinstance(key, bool): offsets.append(key) offsets.sort() return offsets def schedule_end_events(queue: EventQueue, account: Account, offsets: List[int], send_schedule: Dict, not_before: int) -> None: """Push relative-offset reminders and the end notification for account's current end_date.""" for offset in offsets: event_time = account.end_date + offset # Skip reminders that fall before `not_before` (in the past relative to a renewal) # or before `account.begin_date` (an expiry warning before the account even starts). if event_time >= not_before and event_time >= account.begin_date: queue.push(event_time, OFFSET, offset, account.name, account.version) # Only schedule the expiry email if "end" is configured and not already in the past. if "end" in send_schedule and account.end_date >= not_before: queue.push(account.end_date, END, 0, account.name, account.version)Part (b): apply plan changes immediately
Each entry in
changesis validated and pushed into the sameEventQueuewith bucketCHANGED(0) for plan switches orRENEWED(1) for extensions.Because
CHANGED = 0is the smallest bucket number, a plan change at timestamptis guaranteed to pop before anyRENEWED(1),START(2),OFFSET(3), orEND(4) event at timestampt. When it pops, we updateaccount.plan = payload["new_plan"]and emit[Changed]. Every subsequent event—even at the exact same timestampt—reads the updatedaccount.planautomatically.from typing import Dict def queue_change(queue: EventQueue, accounts: Dict[str, Account], change: dict) -> None: """Validate one plan-change or renewal dict and push it onto the event queue.""" name = change["name"] if name not in accounts: raise ValueError(f"change for unknown account {name!r}") is_plan_change = "new_plan" in change is_renewal = "extension" in change # Each change entry must represent either a plan switch or a renewal, never both or neither. if is_plan_change == is_renewal: raise ValueError(f"a change needs exactly one of new_plan / extension: {change!r}") if is_renewal and change["extension"] < 0: raise ValueError(f"negative extension: {change!r}") bucket = CHANGED if is_plan_change else RENEWED queue.push(change["change_date"], bucket, 0, name, change) def format_line(time: int, label: str, account: Account) -> str: """Render one notification using the account's current plan at emission time.""" return f"{time}: [{label}] Subscription for {account.name} ({account.plan})"Part (c): handle renewals with versioned lazy deletion
When a renewal pops at timestamp
t, the old reminders and"end"event sitting inside the heap now point to an outdatedend_date. Searching a binary heap to delete an arbitrary element takesO(E)time, which would slow down renewals.Instead, we use lazy deletion with a per-account version counter:
- Every
Accountstarts atversion = 0. - Whenever
schedule_end_eventspushes anOFFSETorENDevent, it stampsaccount.versioninto the event'spayload. - When a
RENEWEDevent pops at timestampt, we addextensiontoaccount.end_date, incrementaccount.version += 1, and callschedule_end_events(..., not_before=t)to push fresh events stamped with the new version. - Later, when an old
OFFSETorENDevent eventually reaches the top of the heap,payload != account.versioncatches that it is stale, andcontinuediscards it inO(1)time.
Passing
not_before=ton renewal is critical for two reasons: we should never send a newly calculated reminder for a day that already passed, and pushing a timestamp< tinto the heap would emit an out-of-order timestamp backwards in time.- Every
Trace a renewal and same-day plan change
Suppose Clara (
Silver, days2..22) and Devon (Gold, days5..12) use{"start": "Activated", -7: "7d Notice", "end": "Ended"}, with three changes:- Day 10: Clara extends by 14 days.
- Day 12: Devon extends by 5 days.
- Day 12: Devon changes plan to
"Platinum"(even if listed after the renewal inchanges).
Popped heap event State / version check Emitted line ------------------------------- --------------------------------------- ---------------------------------------------- (2, START, 0, "Clara", -) Clara plan=Silver 2: [Activated] Subscription for Clara (Silver) (5, START, 0, "Devon", -) Devon plan=Gold 5: [Activated] Subscription for Devon (Gold) (5, OFFSET, -7, "Devon", v0) v0 == Devon.v0 (valid) 5: [7d Notice] Subscription for Devon (Gold) (10, RENEWED, 0, "Clara", -) end 22->36, v0->v1; push (29,v1),(36,v1) 10: [Renewed] Subscription for Clara (Silver) (12, CHANGED, 0, "Devon", -) bucket 0 < 1: plan Gold -> Platinum 12: [Changed] Subscription for Devon (Platinum) (12, RENEWED, 0, "Devon", -) end 12->17, v0->v1; 17-7=10 < 12 skip; 12: [Renewed] Subscription for Devon (Platinum) push (17, END, v1) (12, END, 0, "Devon", v0) v0 != Devon.v1 -> STALE, skip! (nothing emitted) (15, OFFSET, -7, "Clara", v0) v0 != Clara.v1 -> STALE, skip! (nothing emitted) (17, END, 0, "Devon", v1) v1 == Devon.v1 (valid) 17: [Ended] Subscription for Devon (Platinum) (22, END, 0, "Clara", v0) v0 != Clara.v1 -> STALE, skip! (nothing emitted) (29, OFFSET, -7, "Clara", v1) v1 == Clara.v1 (valid) 29: [7d Notice] Subscription for Clara (Silver) (36, END, 0, "Clara", v1) v1 == Clara.v1 (valid) 36: [Ended] Subscription for Clara (Silver)Look closely at day 12 for Devon:
CHANGED(bucket 0) pops beforeRENEWED(bucket 1), so Devon's[Renewed]message already displays(Platinum). ThenRENEWEDbumpsDevon.versionto1before(12, END, "Devon", v0)(bucket 4) pops, cleanly suppressing Devon's old day-12 expiration!Complete solution
Putting all four phases together gives the complete scheduler:
from typing import Dict, List, Optional import heapq # Priority buckets for events sharing the same timestamp; smaller integer pops first. # Order required by the spec: Changed -> Renewed -> start -> offsets -> end. CHANGED = 0 RENEWED = 1 START = 2 OFFSET = 3 END = 4 class Account: """Mutable state of a single user's subscription as the timeline advances.""" def __init__(self, name: str, plan: str, begin_date: int, end_date: int): self.name = name self.plan = plan self.begin_date = begin_date self.end_date = end_date # Incremented on every renewal so older end-relative events in the heap become stale. self.version = 0 class EventQueue: """Min-heap of scheduled events ordered deterministically by tie-breaking rules.""" def __init__(self): # heap: min-heap of (time, bucket, offset, name, seq, payload) tuples. self.heap = [] # Monotonically increasing tie-breaker preserving input order for identical keys. self.next_seq = 0 def push(self, time: int, bucket: int, offset: int, name: str, payload) -> None: # Including `self.next_seq` before `payload` guarantees Python never compares `payload` # dicts directly (which would raise TypeError when earlier tuple fields tie). entry = (time, bucket, offset, name, self.next_seq, payload) heapq.heappush(self.heap, entry) self.next_seq += 1 def pop(self): time, bucket, offset, name, _, payload = heapq.heappop(self.heap) return time, bucket, offset, name, payload def __len__(self) -> int: return len(self.heap) def load_accounts(user_accounts: List[dict]) -> Dict[str, Account]: """Validate raw account dicts and build a lookup table keyed by unique account name.""" # accounts: dict mapping account_name -> Account(name, plan, begin_date, end_date, version) accounts: Dict[str, Account] = {} for row in user_accounts: name = row["name"] if name in accounts: raise ValueError(f"duplicate account name {name!r}") duration = row["duration"] if duration < 0: raise ValueError(f"negative duration for {name!r}") begin_date = row["account_date"] end_date = begin_date + duration accounts[name] = Account(name, row["plan"], begin_date, end_date) return accounts def relative_offsets(send_schedule: Dict) -> List[int]: """Extract integer day offsets from send_schedule sorted from most negative to least.""" offsets: List[int] = [] for key in send_schedule: # Exclude bool because bool is a subclass of int in Python (True == 1, False == 0). if isinstance(key, int) and not isinstance(key, bool): offsets.append(key) offsets.sort() return offsets def schedule_end_events(queue: EventQueue, account: Account, offsets: List[int], send_schedule: Dict, not_before: int) -> None: """Push relative-offset reminders and the end notification for account's current end_date.""" for offset in offsets: event_time = account.end_date + offset # Skip reminders that fall before `not_before` (in the past relative to a renewal) # or before `account.begin_date` (an expiry warning before the account even starts). if event_time >= not_before and event_time >= account.begin_date: queue.push(event_time, OFFSET, offset, account.name, account.version) # Only schedule the expiry email if "end" is configured and not already in the past. if "end" in send_schedule and account.end_date >= not_before: queue.push(account.end_date, END, 0, account.name, account.version) def queue_change(queue: EventQueue, accounts: Dict[str, Account], change: dict) -> None: """Validate one plan-change or renewal dict and push it onto the event queue.""" name = change["name"] if name not in accounts: raise ValueError(f"change for unknown account {name!r}") is_plan_change = "new_plan" in change is_renewal = "extension" in change # Each change entry must represent either a plan switch or a renewal, never both or neither. if is_plan_change == is_renewal: raise ValueError(f"a change needs exactly one of new_plan / extension: {change!r}") if is_renewal and change["extension"] < 0: raise ValueError(f"negative extension: {change!r}") bucket = CHANGED if is_plan_change else RENEWED queue.push(change["change_date"], bucket, 0, name, change) def format_line(time: int, label: str, account: Account) -> str: """Render one notification using the account's current plan at emission time.""" return f"{time}: [{label}] Subscription for {account.name} ({account.plan})" def send_emails(user_accounts: List[dict], send_schedule: Dict, changes: Optional[List[dict]] = None) -> List[str]: # Phase 1: validate inputs and initialize per-account mutable state. accounts = load_accounts(user_accounts) offsets = relative_offsets(send_schedule) queue = EventQueue() # Phase 2: seed the heap with each account's baseline start, offset, and end events. for account in accounts.values(): if "start" in send_schedule: queue.push(account.begin_date, START, 0, account.name, None) schedule_end_events(queue, account, offsets, send_schedule, account.begin_date) # Phase 3: enqueue all plan changes and renewals into the same timeline. for change in changes or []: queue_change(queue, accounts, change) # Phase 4: pop events in chronological + tie-break order and emit notifications. lines: List[str] = [] while queue: time, bucket, offset, name, payload = queue.pop() account = accounts[name] if bucket == CHANGED: # Update plan immediately; later events at the same timestamp read this new plan. account.plan = payload["new_plan"] label = "Changed" elif bucket == RENEWED: # Extend from the current end_date, invalidate older end-relative events by bumping # version, and schedule fresh reminders/end from the current renewal `time` onward. account.end_date += payload["extension"] account.version += 1 schedule_end_events(queue, account, offsets, send_schedule, not_before=time) label = "Renewed" elif bucket == START: label = send_schedule["start"] elif payload != account.version: # Lazy deletion: this OFFSET or END event belonged to an older end_date before renewal. continue elif bucket == OFFSET: label = send_schedule[offset] else: label = send_schedule["end"] lines.append(format_line(time, label, account)) return lines✅ Submit now — all tests should pass.
Intuition & how it works
Think of the scheduler as a physical desk calendar pile of reminder cards sorted by date and priority. Instead of storing a customer's plan name on every reminder card (which would require hunting through the pile to rewrite cards whenever they upgrade), each card only writes down the customer's name, and we check their live folder at the moment we pull the card off the top. Similarly, when a customer renews their subscription, we do not dig through the pile to rip up their old expiry cards; instead, we use lazy deletion—a technique where outdated items are left in place and ignored later when popped—by bumping an "edition number" (version) on their folder and tossing any card stamped with an older edition.
The obvious naive approach—looping through every single calendar day from the earliest signup to the final expiration—wastes work proportional to the number of days spanned, taking thousands of empty steps for a single multi-year subscription. Trying to generate all events up front and sort them once also falls short, because renewals dynamically shift expiration dates and spawn brand-new reminder timestamps mid-stream. Putting events in a min-heap (a priority queue data structure that always gives you the smallest item in logarithmic time and supports fast insertions) lets us jump straight to active dates while inserting newly extended reminders on the fly.
Walk through a tiny example: Clara signs up on day 2 for 20 days (Silver plan, initial end_date = 22, version = 0) with schedule {"start": "Activated", -7: "7d Notice", "end": "Ended"}, and extends for +14 days on day 10:
- Initially we push
(2, START),(15, OFFSET -7, v0),(22, END, v0), and the renewal(10, RENEWED). - Day
2:(2, START)pops and emits2: [Activated] Subscription for Clara (Silver). - Day
10:(10, RENEWED)pops, updatesend_dateto36, bumpsversionto1, pushes(29, OFFSET -7, v1)and(36, END, v1), and emits10: [Renewed] Subscription for Clara (Silver). - Days
15and22: the oldv0cards pop, failv0 == 1, and are silently discarded; then days29and36pop withv1and emit the updated reminder and expiration.
Complexity
Let N be the number of accounts, M be the number of change/renewal events, and K be the number of integer offset keys in send_schedule.
- Time:
O(E log E), whereE <= N * (K + 2) + M * (K + 2). Each of theNaccounts initially pushes at most1start,Koffset reminders, and1end event, while each of theMchanges pushes1state-change event and (if it is a renewal) at mostK + 1replacement end-relative events. Every event is pushed into and popped from the min-heap once atO(log E)per operation, and dictionary lookups onaccountstakeO(1)time. WhenKis a small constant (such as 2 or 3 email templates), this simplifies toO((N + M) log(N + M)). - Space:
O(N + E). Storing theAccountlookup table usesO(N)memory, and the min-heap plus returned output list hold at mostO(E)entries (including stale pre-renewal events waiting to be popped and discarded).
Edge cases
- Reminder landing before signup (
duration = 8, offset-10):end_date + offsetfalls ataccount_date - 2, soevent_time >= account.begin_dateskips it both initially and after pre-signup renewals. - Zero-day duration (
duration = 0):"start"and"end"share the same timestamp; bucket ordering (START = 2 < END = 4) emits the activation email before the expiration email. - Renewal on the exact expiration day:
RENEWED(bucket = 1) pops beforeEND(bucket = 4) at that timestamp, incrementsaccount.version, and causes the old"end"event at the same timestamp to be skipped as stale. - Renewal after the account already expired:
end_datestill extends from the oldend_date(end_date += extension), andnot_before = renewal_timeskips any recomputed notifications that still fall beforerenewal_time. - Zero-day renewal (
extension = 0):versionincrements, past reminders are skipped bynot_before, and future reminders replace their now-stale older version so nothing is emitted twice. - Multiple changes for one account at the same timestamp:
CHANGED(0) runs beforeRENEWED(1), and ties within the same bucket preserve input order vianext_seq(which sorts identical(time, bucket, offset, name)prefixes in lexicographical order, meaning left-to-right element-by-element comparison). - Missing schedule keys or boolean keys: omitting
"start"or"end"cleanly suppresses those emails while still emitting[Changed]and[Renewed]; boolean keys likeTrueare ignored rather than treated as integer offset1. - Invalid inputs: duplicate account names, negative durations, unknown accounts in
changes, negative extensions, or ambiguous change entries raiseValueErrorup front before any lines are emitted.
Common mistakes
- Copying
planinto the event when pushing: if"Silver"is baked into the day-15 and day-22 tuples at day 2, a plan switch on day 10 fails to update already-queued notifications. Always readaccount.planwhen formatting at pop time. - Sorting offsets as strings or relying on dict iteration order: string comparison puts
"-3"before"-10", whereas numeric comparison correctly puts-10(10 days before expiry) ahead of-3(3 days before expiry). - Forgetting to invalidate pre-renewal events (or deleting them linearly): leaving old events active sends duplicate
"end"lines, while removing them with a list scan makes every renewalO(E)instead ofO(K log E). - Pushing renewed reminders without
not_before = time: if a renewal at day 12 recomputes a reminder at day 10 and pushes10into the heap, day10pops immediately after day12and breaks chronological output order. - Omitting
next_seqbefore dict payloads in heap tuples: when two changes for the same account occur on the same day, Python compares tuple elements left to right and crashes withTypeError: '<' not supported between instances of 'dict' and 'dict'if no unique integer tie-breaker sits ahead ofpayload.
Alternative approaches
- Simulate each account independently, then merge
Nsorted streams: because accounts never interact with one another, you can groupchangesby account name, generate each account's final valid notifications on its own, and merge theNsorted per-account lists withheapq.merge(or one global sort). That takesO(E log E)(orO(M log M + L log N)forLemitted lines), avoids storing stale events across all accounts at once, and partitions cleanly across worker machines byaccount_id. - Day-by-day calendar scan: step
tone day at a time and check every account on every day. Simple to write as a test oracle (tests.pyuses this to verify random schedules), butO(T * (N * K + M))is far too slow when durations span thousands of days.
Follow-up questions
- How would you operate this notification engine in production when billing cycles span months or years? Persist scheduled notifications as rows
(account_id, send_at, bucket, offset, end_version)in a database indexed onsend_at, and have background workers poll due rows. When an extension arrives, wrap updating the account'send_versionand inserting replacement rows inside one database transaction (an all-or-nothing group of database writes) so workers never see half-updated state. Attach an idempotency key (a unique token such asf"{account_id}:{bucket}:{offset}:{end_version}"that an email provider deduplicates) so worker retries after a network timeout never send the same message twice. - How does the design adapt if tier switches and extensions stream in live while notifications are already being dispatched? The min-heap (or
send_atdatabase index) already supports live insertions for any timestamp at or after the current clocknow. You only need an explicit product rule for late-arriving events whosechange_date < now—typically clamping their effective emission timestamp tonowwhile logging the original event timestamp, so downstream consumers never see timestamps move backward. - How would you extend the timeline to handle mid-cycle account cancellations? Introduce a
CANCELLEDstate-change bucket placed alongsideCHANGEDandRENEWEDaccording to product tie-break rules. WhenCANCELLEDpops atchange_date, bumpaccount.versionto invalidate all pending reminders and the future"end"email, mark the account inactive, and emit[Cancelled]. Also clarify with product whether a subsequent extension is allowed to reactivate a cancelled subscription (starting frommax(end_date, change_date)) or should be rejected.
Follow-up questions
- How would you operate this notification engine in production when billing cycles span months or years?
- How does the design adapt if tier switches and extensions stream in live while notifications are already being dispatched?
- How would you extend the timeline to handle mid-cycle account cancellations?
Similar questions
- Pull Request Reviewer Selection via File Ownership
- Task Scheduling with Worker Account Affinity
- Credit-Backed Account Transfer Ledger
- Monthly Invoice Calculator with Tiered Usage
- Merchant Payment Fee Engine for CSV Logs
- Multi-Currency Ledger with Overdraft Coverage
More Stripe interview questions
- Schedule Weekly Release Slots Around Freeze Windows Medium
- Split-Tender Checkout Processor with Expiring Gift Cards Hard
- Rewinding Stream Request Bodies Across HTTP 307/308 Redirects Medium Pro
- Connected User Profiles via Weighted Similarity Medium Pro
- Three-Tier Payment-to-Invoice Reconciliation Medium Pro
- Reconcile Payments Against Invoices Easy Pro
- Post Moderation Policy Engine With Chained Boolean Rules Hard Pro
- Left-to-Right Payment Rule Evaluator with Grouped Conditions Hard Pro
- Spherical Distance and Healthy Region Routing Medium Pro
- Priority-Based Invoice Payment Reconciliation Medium Pro