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 on account_date.
  • Integer day offset k (for instance, -7): label emitted on day end_date + k. Any offset notification that would fall strictly before account_date is suppressed.
  • "end": label emitted on end_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 at change_date and switches the subscriber's active plan to new_plan immediately. The "Changed" line itself, any lower-priority events sharing change_date, and all future notifications for that subscriber must reflect new_plan.
  • Term extension {"name": str, "extension": int, "change_date": int}: emits a "Renewed" notification at change_date using the subscriber's current active plan and increases end_date by extension days (end_date += extension, measured from the current end_date even when change_date > end_date). Every unsent integer-offset reminder and "end" message from the previous end_date (including ones scheduled at change_date) is cancelled, and replacement offset and "end" messages are scheduled for the updated end_date. Any replacement event whose timestamp lands strictly before change_date (or strictly before account_date for 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:

  1. "Changed" events
  2. "Renewed" events
  3. "start" events
  4. Integer-offset events, ordered by numeric offset k from smallest (most negative) to largest
  5. "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_accounts must be unique, duration >= 0, every changes item must reference a known "name" and specify either "new_plan" or "extension" (never both or neither), and extension >= 0. Raise ValueError whenever any of these preconditions is violated.

Step-by-step walkthrough

  1. Understand the timeline and tie-breaking rules

    Each subscription account starts on account_date and initially expires on end_date = account_date + duration. Along that timeline, send_schedule asks us to emit up to three kinds of scheduled emails per account:

    • "start": sent on account_date.
    • Integer offsets (such as -7): sent at end_date + offset (for example, 7 days before expiration).
    • "end": sent on end_date.

    On top of those baseline emails, changes injects live state updates: plan switches (new_plan) and renewals (extension days added to the current end_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 -10 day 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 t shifts end_date forward by extension days from the current end_date (even if the account already expired before t). Any not-yet-sent reminders or "end" email tied to the old end_date are cancelled—including ones scheduled at t itself, because Renewed runs before reminders and expirations at t. Recomputed notifications that would land strictly before t are skipped because time t has already arrived.
    • Input validation: duplicate account names, negative durations, unknown account names in changes, negative extensions, or change dicts with neither/both of new_plan and extension raise ValueError.
    • 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.
  2. 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 all N accounts to see whose start, offset, or end date equals day.

    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.

  3. 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 in O(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 timestamp
    

    Two details in this tuple prevent subtle bugs:

    1. offset stores the raw negative integer (-10 < -3), so more-negative reminders automatically pop before less-negative ones without string-comparison bugs ("-10" vs "-3").
    2. seq is a strictly increasing counter (0, 1, 2, ...). Because two entries never share the same seq, exact ties stay in input order AND Python never compares the payload field at index 5 (comparing two dict payloads in Python raises TypeError).
    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)
    
  4. 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 Account object per user in a dictionary accounts[name]. Queued events carry only account.name, and we read account.plan at the moment the event is popped and formatted.

    schedule_end_events pushes all relative-offset reminders and the "end" event for an account's current end_date. Accepting a not_before cutoff 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 exclude bool keys when scanning send_schedule for integer offsets, because in Python bool is a subclass of int (isinstance(True, int) is True).

    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)
    
  5. Part (b): apply plan changes immediately

    Each entry in changes is validated and pushed into the same EventQueue with bucket CHANGED (0) for plan switches or RENEWED (1) for extensions.

    Because CHANGED = 0 is the smallest bucket number, a plan change at timestamp t is guaranteed to pop before any RENEWED (1), START (2), OFFSET (3), or END (4) event at timestamp t. When it pops, we update account.plan = payload["new_plan"] and emit [Changed]. Every subsequent event—even at the exact same timestamp t—reads the updated account.plan automatically.

    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})"
    
  6. 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 outdated end_date. Searching a binary heap to delete an arbitrary element takes O(E) time, which would slow down renewals.

    Instead, we use lazy deletion with a per-account version counter:

    1. Every Account starts at version = 0.
    2. Whenever schedule_end_events pushes an OFFSET or END event, it stamps account.version into the event's payload.
    3. When a RENEWED event pops at timestamp t, we add extension to account.end_date, increment account.version += 1, and call schedule_end_events(..., not_before=t) to push fresh events stamped with the new version.
    4. Later, when an old OFFSET or END event eventually reaches the top of the heap, payload != account.version catches that it is stale, and continue discards it in O(1) time.

    Passing not_before=t on renewal is critical for two reasons: we should never send a newly calculated reminder for a day that already passed, and pushing a timestamp < t into the heap would emit an out-of-order timestamp backwards in time.

  7. Trace a renewal and same-day plan change

    Suppose Clara (Silver, days 2..22) and Devon (Gold, days 5..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 in changes).
    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 before RENEWED (bucket 1), so Devon's [Renewed] message already displays (Platinum). Then RENEWED bumps Devon.version to 1 before (12, END, "Devon", v0) (bucket 4) pops, cleanly suppressing Devon's old day-12 expiration!

  8. 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:

  1. Initially we push (2, START), (15, OFFSET -7, v0), (22, END, v0), and the renewal (10, RENEWED).
  2. Day 2: (2, START) pops and emits 2: [Activated] Subscription for Clara (Silver).
  3. Day 10: (10, RENEWED) pops, updates end_date to 36, bumps version to 1, pushes (29, OFFSET -7, v1) and (36, END, v1), and emits 10: [Renewed] Subscription for Clara (Silver).
  4. Days 15 and 22: the old v0 cards pop, fail v0 == 1, and are silently discarded; then days 29 and 36 pop with v1 and 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), where E <= N * (K + 2) + M * (K + 2). Each of the N accounts initially pushes at most 1 start, K offset reminders, and 1 end event, while each of the M changes pushes 1 state-change event and (if it is a renewal) at most K + 1 replacement end-relative events. Every event is pushed into and popped from the min-heap once at O(log E) per operation, and dictionary lookups on accounts take O(1) time. When K is a small constant (such as 2 or 3 email templates), this simplifies to O((N + M) log(N + M)).
  • Space: O(N + E). Storing the Account lookup table uses O(N) memory, and the min-heap plus returned output list hold at most O(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 + offset falls at account_date - 2, so event_time >= account.begin_date skips 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 before END (bucket = 4) at that timestamp, increments account.version, and causes the old "end" event at the same timestamp to be skipped as stale.
  • Renewal after the account already expired: end_date still extends from the old end_date (end_date += extension), and not_before = renewal_time skips any recomputed notifications that still fall before renewal_time.
  • Zero-day renewal (extension = 0): version increments, past reminders are skipped by not_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 before RENEWED (1), and ties within the same bucket preserve input order via next_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 like True are ignored rather than treated as integer offset 1.
  • Invalid inputs: duplicate account names, negative durations, unknown accounts in changes, negative extensions, or ambiguous change entries raise ValueError up front before any lines are emitted.

Common mistakes

  • Copying plan into 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 read account.plan when 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 renewal O(E) instead of O(K log E).
  • Pushing renewed reminders without not_before = time: if a renewal at day 12 recomputes a reminder at day 10 and pushes 10 into the heap, day 10 pops immediately after day 12 and breaks chronological output order.
  • Omitting next_seq before 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 with TypeError: '<' not supported between instances of 'dict' and 'dict' if no unique integer tie-breaker sits ahead of payload.

Alternative approaches

  • Simulate each account independently, then merge N sorted streams: because accounts never interact with one another, you can group changes by account name, generate each account's final valid notifications on its own, and merge the N sorted per-account lists with heapq.merge (or one global sort). That takes O(E log E) (or O(M log M + L log N) for L emitted lines), avoids storing stale events across all accounts at once, and partitions cleanly across worker machines by account_id.
  • Day-by-day calendar scan: step t one day at a time and check every account on every day. Simple to write as a test oracle (tests.py uses this to verify random schedules), but O(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 on send_at, and have background workers poll due rows. When an extension arrives, wrap updating the account's end_version and 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 as f"{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_at database index) already supports live insertions for any timestamp at or after the current clock now. You only need an explicit product rule for late-arriving events whose change_date < now—typically clamping their effective emission timestamp to now while 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 CANCELLED state-change bucket placed alongside CHANGED and RENEWED according to product tie-break rules. When CANCELLED pops at change_date, bump account.version to 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 from max(end_date, change_date)) or should be rejected.

Follow-up questions

Similar questions

More Stripe interview questions

All 139 Stripe questions →