Build Sorted Email Event Timeline for Subscriptions
Arrays & HashingAuto-graded · 21 test casesLast updated
Tests date arithmetic, multi-level sort stability, and designing a rule system that cleanly handles event ordering and extensibility.
You're implementing an automated email system for a subscription service. Given customer subscription data, produce a chronological timeline of all emails the system needs to send.
Each subscription record is a list with three elements:
- Customer name (string)
- Start date in ISO format
YYYY-MM-DD(string) - Subscription length in days (integer)
Your system sends two emails per subscription:
- A welcome email sent on the subscription start date
- An expiration email sent when the subscription ends
Calculate the end date by adding the subscription length to the start date. For instance, a subscription beginning 2024-01-10 with length 7 days ends on 2024-01-17.
Return a list where each element represents one email event: [send_date, email_type, customer_name]
Sort the output by send date first. When multiple emails share the same send date, apply these tie-breaking rules in order:
- Email type: all
"welcome"emails before all"expiration"emails - Customer name: alphabetical order
- Input position: if type and name match, preserve the order from the input list
Constraints
- 1 ≤ number of subscription records ≤ 1000
- Subscription length ≥ 0 (a length of 0 means the subscription starts and ends on the same date)
- All dates are valid ISO-8601 format strings (
YYYY-MM-DD) - Customer names are non-empty strings
- Use a date library for arithmetic; do not manually compute day counts across month boundaries
Examples
Example 1
Input: generate_email_schedule([['Alice', '2024-03-01', 30]])
Output: [['2024-03-01', 'welcome', 'Alice'], ['2024-03-31', 'expiration', 'Alice']]
Example 2
Input: generate_email_schedule([['Alice', '2024-03-01', 30], ['Bob', '2024-03-15', 10]])
Output: [['2024-03-01', 'welcome', 'Alice'], ['2024-03-15', 'welcome', 'Bob'], ['2024-03-25', 'expiration', 'Bob'], ['2024-03-31', 'expiration', 'Alice']]
Example 3
Input: generate_email_schedule([['Zoe', '2024-01-31', 1], ['Amy', '2024-01-30', 2], ['Ben', '2024-01-31', 0]])
Output: [['2024-01-30', 'welcome', 'Amy'], ['2024-01-31', 'welcome', 'Ben'], ['2024-01-31', 'welcome', 'Zoe'], ['2024-01-31', 'expiration', 'Ben'], ['2024-02-01', 'expiration', 'Amy'], ['2024-02-01', 'expiration', 'Zoe']]
Hints
Hint 1
Create all email events upfront, then apply a single sort with a compound key that captures all ordering requirements.
Hint 2
Python's datetime.timedelta handles date arithmetic correctly across month and year boundaries—use it instead of manual day counting.
Hint 3
Track the original position of each record so you can break ties between identical customer names and email types by input order.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The solution uses a generate-and-sort pattern:
-
Create all email events upfront: Iterate through each subscription record and generate exactly two email events. The welcome email uses the start date directly. The expiration email uses a computed end date, calculated by adding the subscription length to the start date using
timedelta. -
Augment events with sort keys: Each event is stored as a tuple containing the date, a type rank (0 for welcome, 1 for expiration), the customer name, the original input index, and the email type string. This structure embeds all the information needed for sorting and output formatting.
-
Sort by composite key: Sort all events using a tuple key:
(date, type_rank, customer_name, input_index). Python's tuple comparison naturally implements the required multi-level ordering—earlier dates first, then welcome before expiration, then alphabetical by name, then by input order. -
Extract output fields: Transform the sorted events into the required output format by pulling out the send date (converted back to ISO string), email type, and customer name.
Correctness: The timedelta approach correctly handles all calendar edge cases including month boundaries, year boundaries, and leap years. The composite sort key guarantees deterministic ordering even when multiple subscriptions have identical properties.
Extensibility: Adding new email types (like a reminder before expiration) requires only inserting additional events with appropriate type ranks and dates—the sorting mechanism remains unchanged.
Complexity:
- Time: O(n log n) where n is the number of input records. Generating 2n events is O(n), and sorting them is O(n log n).
- Space: O(n) for storing all generated events before sorting.
from datetime import date, timedelta
from typing import List
def generate_email_schedule(records: List[List]) -> List[List[str]]:
events = []
for idx, record in enumerate(records):
customer, start_date_str, duration = record
start = date.fromisoformat(start_date_str)
expiry = start + timedelta(days=duration)
events.append((start, 0, customer, idx, "welcome"))
events.append((expiry, 1, customer, idx, "expiration"))
events.sort(key=lambda e: (e[0], e[1], e[2], e[3]))
return [[e[0].isoformat(), e[4], e[2]] for e in events]