KatInterview

Subscription Windows: Purchase Attribution and Anomaly Report

Greedy & IntervalsAuto-graded · 15 test cases
MediumAuto-gradedGreedy & Intervalsintervalsmerge-intervalshash-map

Last updated

Merge each user's subscription intervals, then attribute purchases to the merged windows, count September active days, and report out-of-window and overlap anomalies.

Subscription Windows: Purchase Attribution and Anomaly Report

A store logs user activity events and keeps a table of subscription periods. Build a per-user report for September 2025 that shows how much purchase revenue was earned while the user was subscribed, how long they were subscribed, and which purchases or subscription records look suspicious.

Input

compute_subscription_report(events, subscriptions) receives two lists of dictionaries.

events: each item has

  • user_id (int)
  • ts: event time, either an ISO-8601 string such as "2025-09-09T22:00:00Z" or a datetime. A value with no timezone is treated as UTC.
  • event: one of "view", "add_to_cart", "purchase"
  • product_id (int)
  • price_usd (number)

subscriptions: each item has

  • user_id (int)
  • plan (str, not used in the computation)
  • start_ts: start time, in the same formats as above
  • end_ts: end time in the same formats, or None if the subscription has no end yet

All times are interpreted in UTC.

Rules

  1. Intervals are half-open. A subscription covers [start_ts, end_ts). A purchase exactly at start_ts is inside, and a purchase exactly at end_ts is outside.
  2. Open-ended subscriptions. If end_ts is None, the subscription never ends.
  3. Invalid rows. A subscription row with start_ts >= end_ts is discarded completely, as if it did not exist.
  4. Merging. For each user, combine their remaining subscription intervals into the minimal set of disjoint intervals. Two intervals are combined when they overlap, when one contains the other, or when one starts exactly where the other ends (next_start <= current_end). A user is marked as an overlap user if at least one such combination happened.
  5. Purchase attribution. Only events with event == "purchase" matter for revenue. Every purchase is checked against the user's merged intervals regardless of its month. If it falls inside one, its price is added to that user's subscribed_purchase_revenue. Otherwise it increments the user's out_of_window_purchases and produces an outside_window anomaly. A user with no valid subscriptions has all purchases out of window.
  6. Active days. Intersect each merged interval with the September window [2025-09-01T00:00Z, 2025-10-01T00:00Z), add up the durations in seconds, and take floor(total_seconds / 86400).
  7. Which users get a row. Every user who has at least one valid (non-discarded) subscription row, or who appears in any event of any type, gets exactly one row. Rows are sorted by user_id ascending.

Output

Return a dictionary with two keys.

"user_month_agg": a list with one dict per user:

  • user_id
  • month: always "2025-09"
  • active_subscription_days (int)
  • subscribed_purchase_revenue (float, 0.0 if none)
  • out_of_window_purchases (int)

"anomalies": a list of dicts with keys user_id, ts, price_usd, reason, in this order:

  1. First, one outside_window entry per out-of-window purchase, in the order the purchases appear in events. ts and price_usd are the original values from the event, unchanged.
  2. Then, one entry per overlap user, sorted by user_id, with reason = "overlap_fixed", ts = None and price_usd = None. Each overlap user appears once, however many merges happened.

Constraints

  • 0 <= len(events), len(subscriptions) <= 10^5
  • Timestamps are valid ISO-8601 strings or datetime objects.
  • price_usd is non-negative.
  • A user may have any number of subscription rows, in any order, and they may overlap or nest.
  • Sum revenue as floats in event order.

Examples

Example 1

Input: compute_subscription_report([{'user_id': 1, 'ts': '2025-09-09T22:00:00Z', 'event': 'purchase', 'product_id': 101, 'price_usd': 19.99}, {'user_id': 1, 'ts': '2025-09-15T03:00:00Z', 'event': 'purchase', 'product_id': 102, 'price_usd': 5}, {'user_id': 2, 'ts': '2025-09-01T01:00:00Z', 'event': 'purchase', 'product_id': 103, 'price_usd': 9.99}], [{'user_id': 1, 'plan': 'pro', 'start_ts': '2025-08-28T00:00:00Z', 'end_ts': '2025-09-10T00:00:00Z'}, {'user_id': 1, 'plan': 'pro', 'start_ts': '2025-09-10T00:00:00Z', 'end_ts': '2025-10-10T00:00:00Z'}, {'user_id': 2, 'plan': 'basic', 'start_ts': '2025-09-05T12:00:00Z', 'end_ts': None}])

Output: {'user_month_agg': [{'user_id': 1, 'month': '2025-09', 'active_subscription_days': 30, 'subscribed_purchase_revenue': 24.99, 'out_of_window_purchases': 0}, {'user_id': 2, 'month': '2025-09', 'active_subscription_days': 25, 'subscribed_purchase_revenue': 0, 'out_of_window_purchases': 1}], 'anomalies': [{'user_id': 2, 'ts': '2025-09-01T01:00:00Z', 'price_usd': 9.99, 'reason': 'outside_window'}, {'user_id': 1, 'ts': None, 'price_usd': None, 'reason': 'overlap_fixed'}]}

Hints

Hint 1

Group subscription rows by user, drop rows where start >= end, treat a missing end as a very large datetime, then sort each user's intervals by start.

Hint 2

Sweep the sorted intervals and keep a list of merged ones. If the next start is <= the last merged end, extend the end if needed (never shrink it) and remember the user as an overlap user. Touching intervals count too.

Hint 3

Test each purchase against the merged intervals only, using start <= ts < end. For active days, clip each merged interval to [Sep 1, Oct 1), sum seconds, then floor-divide by 86400. Don't forget users who only appear in events.