Subscription Windows: Purchase Attribution and Anomaly Report
Greedy & IntervalsAuto-graded · 15 test casesLast 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 adatetime. 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 aboveend_ts: end time in the same formats, orNoneif the subscription has no end yet
All times are interpreted in UTC.
Rules
- Intervals are half-open. A subscription covers
[start_ts, end_ts). A purchase exactly atstart_tsis inside, and a purchase exactly atend_tsis outside. - Open-ended subscriptions. If
end_tsisNone, the subscription never ends. - Invalid rows. A subscription row with
start_ts >= end_tsis discarded completely, as if it did not exist. - 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. - 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'ssubscribed_purchase_revenue. Otherwise it increments the user'sout_of_window_purchasesand produces anoutside_windowanomaly. A user with no valid subscriptions has all purchases out of window. - 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 takefloor(total_seconds / 86400). - 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_idascending.
Output
Return a dictionary with two keys.
"user_month_agg": a list with one dict per user:
user_idmonth: always"2025-09"active_subscription_days(int)subscribed_purchase_revenue(float,0.0if none)out_of_window_purchases(int)
"anomalies": a list of dicts with keys user_id, ts, price_usd, reason, in this order:
- First, one
outside_windowentry per out-of-window purchase, in the order the purchases appear inevents.tsandprice_usdare the original values from the event, unchanged. - Then, one entry per overlap user, sorted by
user_id, withreason = "overlap_fixed",ts = Noneandprice_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
datetimeobjects. price_usdis 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.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
- Normalize time. Convert every timestamp to a timezone-aware UTC
datetime. Treat naive values as UTC and treat a missingend_tsas the largest representable datetime. - Group and clean. Group subscription rows by user and discard rows where
start >= end. - Merge intervals. Sort each user's intervals by start and sweep through them. If the next start is
<=the end of the last merged interval, the two overlap or touch. Extend the last end if the new end is later (it never shrinks, which handles nested intervals) and mark the user as an overlap user. Otherwise open a new merged interval. - Attribute purchases. For each purchase event, check whether
start <= ts < endfor any of the user's merged intervals. If so, add the price to revenue. If not, bump the out-of-window counter and record anoutside_windowanomaly with the originaltsandprice_usd. Every user seen in any event is added to the user set. - Count active days. Clip each merged interval to
[Sep 1, Oct 1), sum the surviving durations in seconds, and floor-divide by 86400. - Assemble output. Produce one row per user, sorted by id. Anomalies are the
outside_windowentries in event order, followed by oneoverlap_fixedentry per overlap user, sorted by id.
Why it is correct
- After sorting by start, any interval that overlaps or touches the current merged block must come next in the sweep, so one pass yields the minimal disjoint cover.
- Attributing purchases against disjoint merged intervals means a purchase is matched at most once, so revenue is never double-counted.
- Computing active time on merged intervals means overlapping time is counted once.
- Half-open comparisons put a purchase at a renewal boundary in the new interval and a purchase at a final end time outside.
- Clipping with
max(start, Sep 1)andmin(end, Oct 1)handles subscriptions that begin before September, extend beyond it, or never end.
Complexity
With S subscription rows, E events, and k merged intervals per user:
- Time: O(S log S) for sorting plus O(E * k) for attribution, which is close to linear because k is small. Binary search over merged starts would make attribution O(E log k).
- Space: O(S + U + A), where U is the number of users and A the number of anomalies.
Reference solution
from datetime import datetime, timezone
from typing import Dict, List
def _parse_ts(value):
if value is None:
return None
if isinstance(value, datetime):
dt = value
else:
dt = datetime.fromisoformat(value.replace("Z", "+00:00"))
if dt.tzinfo is None:
dt = dt.replace(tzinfo=timezone.utc)
return dt.astimezone(timezone.utc)
def compute_subscription_report(events: List[Dict], subscriptions: List[Dict]) -> Dict:
month_start = datetime(2025, 9, 1, tzinfo=timezone.utc)
month_end = datetime(2025, 10, 1, tzinfo=timezone.utc)
far_future = datetime.max.replace(tzinfo=timezone.utc)
grouped = {}
for row in subscriptions:
start = _parse_ts(row["start_ts"])
end = _parse_ts(row.get("end_ts")) or far_future
if start < end:
grouped.setdefault(row["user_id"], []).append((start, end))
merged = {}
overlap_users = set()
for user_id, intervals in grouped.items():
intervals.sort()
out = []
for start, end in intervals:
if out and start <= out[-1][1]:
overlap_users.add(user_id)
if end > out[-1][1]:
out[-1] = (out[-1][0], end)
else:
out.append((start, end))
merged[user_id] = out
users = set(grouped)
anomalies = []
revenue = {}
outside_count = {}
for event in events:
user_id = event["user_id"]
users.add(user_id)
if event["event"] != "purchase":
continue
ts = _parse_ts(event["ts"])
price = float(event["price_usd"])
inside = any(s <= ts < e for s, e in merged.get(user_id, []))
if inside:
revenue[user_id] = revenue.get(user_id, 0.0) + price
else:
outside_count[user_id] = outside_count.get(user_id, 0) + 1
anomalies.append({
"user_id": user_id,
"ts": event["ts"],
"price_usd": event["price_usd"],
"reason": "outside_window",
})
rows = []
for user_id in sorted(users):
active_seconds = 0.0
for start, end in merged.get(user_id, []):
left = max(start, month_start)
right = min(end, month_end)
if left < right:
active_seconds += (right - left).total_seconds()
rows.append({
"user_id": user_id,
"month": "2025-09",
"active_subscription_days": int(active_seconds // 86400),
"subscribed_purchase_revenue": revenue.get(user_id, 0.0),
"out_of_window_purchases": outside_count.get(user_id, 0),
})
for user_id in sorted(overlap_users):
anomalies.append({"user_id": user_id, "ts": None, "price_usd": None, "reason": "overlap_fixed"})
return {"user_month_agg": rows, "anomalies": anomalies}