KatInterview

Build Sorted Email Event Timeline for Subscriptions

Arrays & HashingAuto-graded · 21 test cases
MediumAuto-gradedArrays & Hashingsortingdatessimulation

Last 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:

  1. Email type: all "welcome" emails before all "expiration" emails
  2. Customer name: alphabetical order
  3. 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.