Event-Driven Email Notification System with Account Updates
Data Structure DesignModel answerLast updated
Build a scheduler that emits subscription notifications in time order, handling plan switches and subscription extensions with deterministic tie-breaking.
You're building an automated email system for a subscription service. The system must schedule and emit notification messages based on account lifecycles, plan modifications, and subscription extensions.
Input:
-
send_schedule: A dictionary mapping when to send notifications:"start": Label for the account start date- Negative integers (e.g.,
-7,-30): Labels for notifications sent that many days before expiration "end": Label for the expiration date
-
user_accounts: List of account records, each containing:name: Account identifier (string)plan: Plan type (string)account_date: Start day (integer)duration: Subscription length in days (integer)
-
changes(optional): List of updates, each being either:- Plan switch:
{name, new_plan, change_date} - Extension:
{name, extension, change_date}(adds days to subscription)
- Plan switch:
Output:
Emit all notifications as text lines in chronological order:
<day>: [<Label>] Subscription for <name> (<plan>)
Tie-breaking rules when multiple events occur on the same day:
- State updates first: plan switches, then extensions (in that order)
- Start notifications
- Pre-expiration warnings (sorted by offset: -30 before -7)
- End notifications
- Within each category, alphabetical by account name
Requirements:
- Part A: Generate baseline notifications (start, offset warnings, end) for all accounts
- Part B: Handle plan switches—update takes effect immediately, all notifications from that point forward reflect the new plan
- Part C: Handle extensions—recalculate expiration and all future offset/end notifications based on the new expiration date
Example:
send_schedule = {"start": "Welcome", -15: "Expiring Soon", "end": "Expired"}
accounts = [
{"name": "alice", "plan": "Basic", "account_date": 0, "duration": 30}
]
changes = [
{"name": "alice", "new_plan": "Premium", "change_date": 10}
]
Output includes:
0: [Welcome] Subscription for alice (Basic)
10: [Changed] Subscription for alice (Premium)
15: [Expiring Soon] Subscription for alice (Premium)
30: [Expired] Subscription for alice (Premium)
Describe your data structures, algorithm, and time complexity. State any assumptions clearly.
Hints
Hint 1
Use a priority queue keyed by (time, event_type, name) to merge all notification streams efficiently
Hint 2
When an extension occurs, previously scheduled offset and end notifications become invalid—use versioning to identify stale events
Hint 3
Plan switches must fire before any other event at the same timestamp to ensure subsequent notifications reflect the updated plan
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This problem is best modeled as a discrete-event simulation using a priority queue. Every notification and state change becomes an event that fires at a specific time.
Core Strategy
1. Event representation
Each event is keyed by a tuple that encodes both timing and tie-breaking priority:
(timestamp, category, subcategory, account_name, sequence_id)
Categories map to the tie-breaking rules:
0: Plan switch1: Extension2: Start notification3: Offset warning (subcategory = offset value for sorting)4: End notification
The sequence_id ensures stable ordering for truly identical events and prevents heap comparison of payload objects.
2. Lazy invalidation for extensions
When an extension occurs, the expiration date changes, invalidating all future offset and end events. Rather than removing events from the heap (expensive), we:
- Assign each account a
versioncounter - Tag each offset/end event with the version it was scheduled under
- Increment version on extension and schedule new events
- Discard events whose version doesn't match when they're popped
3. Immediate plan updates
Plan switches are assigned the lowest category value at their timestamp, guaranteeing they execute first. When formatting any event, we read the account's current plan, so all subsequent events automatically reflect the change.
Data Structures
- Accounts map:
{name -> {plan, start_day, end_day, version}} - Min-heap: Holds all events sorted by the composite key
- Sequence counter: Global monotonic ID for insertion order
Algorithm
Initialization:
- Create account records with initial plan and computed expiration
- For each account, schedule:
- Start event at
start_day(if configured) - Offset events at
end_day + offsetfor each negative offset - End event at
end_day(if configured)
- Start event at
- Schedule all plan switches and extensions from the changes list
Simulation loop:
- Pop the minimum event from the heap
- If it's an offset or end event, check version—skip if stale
- Process the event:
- Plan switch: Update account's plan
- Extension: Increment version, extend
end_day, schedule new offset/end events - Notification: Format and emit the line using current account state
- Continue until heap is empty
Complexity Analysis
Let:
- N = number of accounts
- K = number of offset notifications in the schedule
- M = number of state changes (plan switches + extensions)
- R = number of extensions (R ≤ M)
Time: O((N·K + M·K) log(N·K + M·K))
- Initial scheduling: N accounts × (K+2) events
- Extensions reschedule: up to R × (K+1) new events
- Each stale event costs one pop
- Total heap operations: O((N+M)K), each O(log heap_size)
Space: O(N + (N+M)K) for the account map and heap
Optimization note: Push only the next upcoming event per account, then schedule the following one when it fires. This reduces heap size to O(N+M) but adds complexity—most interviews expect the simpler approach.
Edge Cases
- Zero-duration subscription: Start and end occur simultaneously; start fires first due to category ordering
- Offset notification before start: Skip events where
end_day + offset < start_day - Extension on expiration day: The extension event fires before the end notification (category 1 < 4), so the account doesn't expire
- Multiple extensions: Each invalidates the previous version's tail events
- Plan switch + extension same day, same account: Plan switch fires first (category 0 < 1), so the extension notification shows the new plan
- Offset of 0: Treated as category 3, fires before category 4 end event
- Unknown account name in changes: Ignored
Assumptions
- Account names are unique identifiers
- Extensions are non-negative and extend from the current expiration date
- Notifications scheduled in the past are omitted
- When multiple identical changes target the same account at the same time, apply in input order
Implementation Skeleton
import heapq
class NotificationScheduler:
SWITCH, EXTEND, START, OFFSET, END = 0, 1, 2, 3, 4
def schedule_notifications(self, user_accounts, send_schedule, changes=None):
accounts = {}
heap = []
seq = 0
output = []
# Extract offsets and sort
offsets = sorted(k for k in send_schedule if isinstance(k, int))
def push_event(time, category, sub_key, name, payload):
nonlocal seq
heapq.heappush(heap, (time, category, sub_key, name, seq, payload))
seq += 1
def schedule_tail_events(name, from_time):
"""Schedule offset and end events from current expiration"""
acc = accounts[name]
version = acc["version"]
for offset in offsets:
event_time = acc["expiration"] + offset
if event_time >= max(from_time, acc["start"]):
label = send_schedule[offset]
push_event(event_time, self.OFFSET, offset, name,
("notify", label, version))
if "end" in send_schedule and acc["expiration"] >= from_time:
label = send_schedule["end"]
push_event(acc["expiration"], self.END, 0, name,
("notify", label, version))
# Initialize accounts and baseline events
for account in user_accounts:
name = account["name"]
start = account["account_date"]
expiration = start + account["duration"]
accounts[name] = {
"plan": account["plan"],
"start": start,
"expiration": expiration,
"version": 0
}
if "start" in send_schedule:
push_event(start, self.START, 0, name,
("notify", send_schedule["start"], None))
schedule_tail_events(name, start)
# Schedule state changes
for change in (changes or []):
name = change["name"]
if name not in accounts:
continue
if "new_plan" in change:
push_event(change["change_date"], self.SWITCH, 0, name,
("switch", change["new_plan"]))
elif "extension" in change:
push_event(change["change_date"], self.EXTEND, 0, name,
("extend", change["extension"]))
# Process events
while heap:
time, category, _, name, _, payload = heapq.heappop(heap)
action = payload[0]
if action == "notify":
label, version = payload[1], payload[2]
# Check version for offset/end events
if version is not None and accounts[name]["version"] != version:
continue # Stale event
plan = accounts[name]["plan"]
output.append(f"{time}: [{label}] Subscription for {name} ({plan})")
elif action == "switch":
new_plan = payload[1]
accounts[name]["plan"] = new_plan
output.append(f"{time}: [Changed] Subscription for {name} ({new_plan})")
elif action == "extend":
extension_days = payload[1]
acc = accounts[name]
acc["expiration"] += extension_days
acc["version"] += 1
plan = acc["plan"]
output.append(f"{time}: [Renewed] Subscription for {name} ({plan})")
schedule_tail_events(name, time)
return output
Common Mistakes
- Forgetting tie-breaking rules: Events at the same time must follow the specified priority ordering
- Using current time for offset calculations: Offsets are relative to expiration, not "now"
- Trying to delete heap elements: Use versioning instead
- Updating state after emission: Plan switches must take effect before formatting any event at that timestamp
- Not skipping past-dated events: After an extension, some newly computed events may be in the past
This solution efficiently handles the event merging, state updates, and invalidation while maintaining deterministic ordering throughout.