Coupon Campaign Conversion and 48-Hour Spend Report
SQL & DataAuto-graded · 16 test casesLast updated
Build a per-user cohort from coupon events, then join transactions by time window to compute cohort size, converters, and spend within 48 hours.
Coupon Campaign Report
A shop ran a promotion with the coupon code SUMMER20. You are given two logs, each represented as a list of rows, and must summarize how well the promotion performed.
Inputs
coupon_events: a list of rows[user_id, coupon_code, applied_at].user_idis an integer.coupon_codeis a string.applied_atis an ISO-8601 timestamp string such as"2023-08-01T10:00:00Z".
purchases: a list of rows[transaction_id, user_id, amount, transacted_at].transaction_idanduser_idare integers.amountis a number.transacted_atis an ISO-8601 timestamp string.
Definitions
- Cohort: every user who has at least one coupon event with code exactly
SUMMER20and anapplied_atin August 2023 (from2023-08-01 00:00:00UTC inclusive to2023-09-01 00:00:00UTC exclusive). - Anchor time: for a cohort user, the earliest qualifying (
SUMMER20, August 2023) application time. A user has exactly one anchor, even if they applied the coupon several times. - A purchase counts for a cohort user if it belongs to that user and happened strictly after their anchor time.
- A purchase falls in the 48-hour window if it counts and its time is at most the anchor time plus 48 hours (so a purchase at exactly 48:00:00 after the anchor is included).
Task
Return a dictionary with these three keys:
total_coupon_users: the number of users in the cohort.converted_users: the number of cohort users with at least one counting purchase (at any time after the anchor, with no upper limit).total_gmb_48h: the sum ofamountover all counting purchases of cohort users that fall in the 48-hour window.
Rules
- Timestamps ending in
Zor carrying an offset must be normalized to UTC before comparing. Timestamps with no timezone are treated as UTC. - Coupon events with another code, or outside August 2023, are ignored.
- Purchases by users outside the cohort are ignored.
- Purchases at or before the anchor time are ignored for every metric.
- If the inputs are empty, return
0,0, and0.0respectively.
Constraints
- Both lists may be empty.
- Each user may have several coupon events and several purchases.
- Timestamps are valid ISO-8601 strings.
- Amounts are non-negative numbers.
- Input sizes are such that a single pass over each list is expected.
Examples
Example 1
Input: summarize_coupon_campaign([[1, 'SUMMER20', '2023-08-01T10:00:00Z']], [[101, 1, 50, '2023-08-02T09:00:00Z']])
Output: {'total_coupon_users': 1, 'converted_users': 1, 'total_gmb_48h': 50}
Example 2
Input: summarize_coupon_campaign([[1, 'SUMMER20', '2023-08-01T10:00:00Z'], [2, 'OTHER', '2023-08-05T10:00:00Z']], [[101, 1, 50, '2023-08-02T09:00:00Z']])
Output: {'total_coupon_users': 1, 'converted_users': 1, 'total_gmb_48h': 50}
Example 3
Input: summarize_coupon_campaign([[1, 'SUMMER20', '2023-08-15T10:00:00Z'], [2, 'SUMMER20', '2023-08-20T12:00:00Z']], [[101, 1, 10.5, '2023-08-15T11:00:00Z'], [102, 1, 20.25, '2023-08-17T10:00:00Z'], [103, 2, 7, '2023-08-19T12:00:00Z']])
Output: {'total_coupon_users': 2, 'converted_users': 1, 'total_gmb_48h': 30.75}
Hints
Hint 1
Reduce the coupon events to one anchor time per cohort user first: keep only SUMMER20 events in August 2023 and take the earliest per user. This avoids double counting later.
Hint 2
Normalize all timestamps to timezone-aware UTC datetimes before comparing. Handle a trailing 'Z' explicitly and treat naive values as UTC.
Hint 3
For each purchase, look up its user's anchor in a dictionary. Require time > anchor for conversion, and additionally time <= anchor + 48h for the spend total. Track converters in a set.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
- Build the cohort. Walk through the coupon events. Skip anything that is not
SUMMER20or that falls outside[2023-08-01, 2023-09-01)UTC. For each remaining user, store the earliest application time in a dictionary. That dictionary is the cohort, with exactly one anchor per user. - Scan the purchases. For each purchase, look up the user's anchor. If there is none, skip it. Otherwise parse the time and:
- if it is not strictly after the anchor, ignore it;
- otherwise add the user to a
convertedset; - and if it is also at most
anchor + 48h, add its amount to the running total.
- Return the cohort size, the size of the converted set, and the total.
Why it is correct
- Using the earliest qualifying application gives each user a single anchor, so no one is counted twice no matter how many times they applied.
- Cohort size is taken from the dictionary, so users who never purchase are still counted. This is the behavior a LEFT JOIN gives you in SQL.
- The strict
>comparison excludes purchases at or before the anchor, and the<=upper bound includes a purchase at exactly 48 hours. - Conversion has no upper time limit, while spend does, so a late purchase counts toward
converted_usersbut nottotal_gmb_48h. - Normalizing every timestamp to UTC makes comparisons consistent regardless of the input format.
Complexity
- Time: O(C + P) for C coupon events and P purchases, with O(1) dictionary and set operations.
- Space: O(U) for the anchor dictionary and the converted set, where U is the number of cohort users.
Reference solution
from datetime import datetime, timezone, timedelta
from typing import List, Dict
def summarize_coupon_campaign(coupon_events: List[List], purchases: List[List]) -> Dict[str, float]:
def parse_time(value):
text = value.strip()
if text.endswith('Z'):
text = text[:-1] + '+00:00'
result = datetime.fromisoformat(text)
if result.tzinfo is None:
result = result.replace(tzinfo=timezone.utc)
return result.astimezone(timezone.utc)
august_start = datetime(2023, 8, 1, tzinfo=timezone.utc)
september_start = datetime(2023, 9, 1, tzinfo=timezone.utc)
anchors = {}
for user_id, coupon_code, applied_at in coupon_events:
if coupon_code != 'SUMMER20':
continue
applied = parse_time(applied_at)
if august_start <= applied < september_start:
if user_id not in anchors or applied < anchors[user_id]:
anchors[user_id] = applied
converted = set()
total_gmb = 0.0
for transaction_id, user_id, amount, transacted_at in purchases:
anchor = anchors.get(user_id)
if anchor is None:
continue
when = parse_time(transacted_at)
if when > anchor:
converted.add(user_id)
if when <= anchor + timedelta(hours=48):
total_gmb += float(amount)
return {
'total_coupon_users': len(anchors),
'converted_users': len(converted),
'total_gmb_48h': total_gmb,
}