Daily Campaign Performance Summary Over a Rolling Window
SQL & DataAuto-graded · 14 test casesLast updated
Tests conditional aggregation across multiple related tables, time-window filtering, fan-out avoidance, and safe division when computing per-day engagement rates.
Daily Campaign Performance Summary Over a Rolling Window
You are given three collections of records describing a set of ads, their exposure and engagement events, and downstream conversions.
Input tables
ads — one entry per ad
| Field | Type | Description |
|---|---|---|
ad_id | int | Unique ad identifier |
advertiser_id | int | Owner of the ad |
ad_type | str | Format of the ad (e.g. "image", "video") |
events — one entry per exposure or click event
| Field | Type | Description |
|---|---|---|
event_id | int | Unique event identifier |
ad_id | int | Ad that was shown or clicked |
is_click | int / bool | 1 (or True) if the user clicked, 0 (or False) for a plain view |
event_time | str | Calendar date of the event, "YYYY-MM-DD" |
conversions — one entry per conversion that followed an event
| Field | Type | Description |
|---|---|---|
conv_id | int | Unique conversion identifier |
event_id | int | The originating event |
ad_id | int | Ad that drove the conversion |
conv_time | str | Calendar date of the conversion, "YYYY-MM-DD" |
Task
Given a reference date snapshot_date ("YYYY-MM-DD"), produce a summary covering the 7-day window [snapshot_date − 6 days, snapshot_date], both endpoints inclusive.
For every (calendar_date, ad_id) pair that has at least one event or conversion within the window, return a record containing:
date— the calendar date ("YYYY-MM-DD")ad_id— the ad identifierimpressions— total event rows for that ad on that date (every row counts, whether or not it is a click)clicks— event rows whereis_clickis truthyconversions— conversion rows whoseconv_timefalls on that date for that ad (attributed to the conversion date, not the originating event's date)ctr— click-through rate:clicks / impressions, or0.0whenimpressionsis 0conversion_rate—conversions / clicks, or0.0whenclicksis 0
Only include rows for ad_id values present in ads. Do not emit zero-filled rows for ads or dates with no activity at all. Conversions may exceed clicks on a given day (e.g. from repeat conversions on a later date); do not cap the rate.
Return the list sorted by (date, ad_id) ascending.
Constraints
0 ≤ len(ads) ≤ 10 0000 ≤ len(events) ≤ 500 0000 ≤ len(conversions) ≤ 500 000- All dates are valid ISO-8601 strings (
"YYYY-MM-DD"). snapshot_dateis always a valid date; data outside the 7-day window should be ignored.ad_idvalues ineventsorconversionsthat do not appear inadsmust be ignored.is_clickis0/1orFalse/True; treat it as a boolean.- The same conversion can appear on a different calendar date than its originating event.
ctrandconversion_rateare plain Python floats; no rounding is required.
Examples
Example 1
Input: compute_daily_ad_performance([{'ad_id': 101, 'advertiser_id': 1001, 'ad_type': 'image'}, {'ad_id': 102, 'advertiser_id': 1002, 'ad_type': 'video'}, {'ad_id': 103, 'advertiser_id': 1001, 'ad_type': 'carousel'}], [{'event_id': 1, 'ad_id': 101, 'is_click': 0, 'event_time': '2023-07-01'}, {'event_id': 2, 'ad_id': 101, 'is_click': 1, 'event_time': '2023-07-01'}, {'event_id': 3, 'ad_id': 102, 'is_click': 0, 'event_time': '2023-07-01'}, {'event_id': 4, 'ad_id': 103, 'is_click': 1, 'event_time': '2023-07-02'}], [{'conv_id': 900, 'event_id': 2, 'ad_id': 101, 'conv_time': '2023-07-01'}, {'conv_id': 901, 'event_id': 4, 'ad_id': 103, 'conv_time': '2023-07-02'}, {'conv_id': 902, 'event_id': 2, 'ad_id': 101, 'conv_time': '2023-07-03'}], '2023-07-03')
Output: [{'date': '2023-07-01', 'ad_id': 101, 'impressions': 2, 'clicks': 1, 'conversions': 1, 'ctr': 0.5, 'conversion_rate': 1}, {'date': '2023-07-01', 'ad_id': 102, 'impressions': 1, 'clicks': 0, 'conversions': 0, 'ctr': 0, 'conversion_rate': 0}, {'date': '2023-07-02', 'ad_id': 103, 'impressions': 1, 'clicks': 1, 'conversions': 1, 'ctr': 1, 'conversion_rate': 1}, {'date': '2023-07-03', 'ad_id': 101, 'impressions': 0, 'clicks': 0, 'conversions': 1, 'ctr': 0, 'conversion_rate': 0}]
Hints
Hint 1
Build a set of valid ad IDs from the ads list first so you can filter both tables in O(1) per row.
Hint 2
Aggregate the events table and the conversions table independently into a shared (date, ad_id) dictionary — do not join them row by row, or a single event with multiple conversions will inflate your impression and click counts.
Hint 3
Compute CTR and conversion rate only after all counts are finalised, and guard each division with a check that the denominator is non-zero before dividing.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Core insight: aggregate separately, then merge
The natural instinct is to join the conversions table onto the events table on event_id, then group. That works fine when every event has at most one conversion, but the moment a single click produces two conversions (completely normal in retargeting or multi-touch attribution), a naive join duplicates the event row and overcounts impressions and clicks.
The fix is to treat the two tables as independent fact sources and aggregate them into the same keyed dictionary in two separate passes. The key is (date_string, ad_id). Because both passes write to the same bucket structure, a (date, ad_id) pair that has only conversions and no events that day — or vice versa — is handled correctly without any explicit outer-join logic.
Step-by-step
-
Build a valid-ad set. Collect every
ad_idfrom theadslist into a Pythonset. Membership checks then cost O(1) per row. -
Determine the window. Parse
snapshot_dateinto adateobject. Subtract 6 days to getstart. Bothstartandsnapshot_date(end) are included. -
Pass 1 — events. Iterate every event row. Skip rows whose
ad_idis unknown or whoseevent_timefalls outside the window. For each qualifying row, incrementimpressionsby 1, and also incrementclicksby 1 whenis_clickis truthy. -
Pass 2 — conversions. Iterate every conversion row independently. Apply the same ad-id and window filters, but use
conv_timeas the date key (not the originating event's date). Incrementconversionsby 1. -
Compute rates. After both passes, iterate the dictionary in sorted key order. Set
ctr = clicks / impressions(or0.0), andconversion_rate = conversions / clicks(or0.0). Append each completed row to the output list.
Why this is correct
- Each event row is visited exactly once, so impression and click totals are exact.
- Each conversion row is visited exactly once — no join means no fan-out. Even if event 2 has two conversions, both land in the conversion count without touching the click count.
- Conversions are attributed to their own date, so a repeat conversion on a later day creates (or increments) a bucket for that later day, independent of when the original click happened. A bucket with zero impressions and zero clicks but nonzero conversions is a valid output row, and both rates are
0.0. dict.setdefaultinitialises a bucket on first access and returns the existing one on subsequent accesses, ensuring the two passes merge cleanly.- Sorting by the tuple
(date_str, ad_id)works correctly because ISO-8601 date strings sort chronologically as plain strings.
Complexity
Let A = number of ads, E = number of event rows, C = number of conversion rows, K = number of output groups (distinct (date, ad_id) pairs with activity).
- Time: O(A + E + C + K log K). Building the valid-ad set is O(A). The two linear scans are O(E) and O(C). Sorting the output groups is O(K log K).
- Space: O(A + K). The valid-ad set holds A identifiers; the metrics dictionary holds at most K buckets.
Edge cases
- Conversion with no events that day — bucket is created by Pass 2 with impressions = clicks = 0; both rates are
0.0; row is still emitted. - Conversion rate above 1.0 — possible when repeat conversions arrive on the same day as only one click. The solution does not cap it.
is_clickas bool or int — Python's truthiness handles bothTrue/Falseand1/0identically.- Event or conversion outside the window — skipped by the
in_windowcheck; does not appear in output. - Unknown
ad_id— skipped by the valid-ad set check. - All inputs empty, or nothing in the window — both passes produce no buckets; the function returns
[].
Reference solution
from datetime import date, timedelta
from typing import Dict, List
def compute_daily_ad_performance(
ads: List[Dict],
events: List[Dict],
conversions: List[Dict],
snapshot_date: str,
) -> List[Dict]:
end = date.fromisoformat(snapshot_date)
start = end - timedelta(days=6) # 7-day window, both ends inclusive
# Only report on known ads
valid_ad_ids = {ad["ad_id"] for ad in ads}
# Keyed by (date_str, ad_id) so the two passes share the same buckets
metrics: Dict = {}
def in_window(day_str: str) -> bool:
d = date.fromisoformat(day_str)
return start <= d <= end
# Pass 1 — events: every row is an impression; is_click rows also increment clicks
for ev in events:
ad_id = ev["ad_id"]
day = ev["event_time"]
if ad_id not in valid_ad_ids or not in_window(day):
continue
bucket = metrics.setdefault(
(day, ad_id),
{"date": day, "ad_id": ad_id, "impressions": 0, "clicks": 0, "conversions": 0},
)
bucket["impressions"] += 1
if ev["is_click"]:
bucket["clicks"] += 1
# Pass 2 — conversions: attributed to conv_time, not to the originating event's date
# Processed separately to avoid fan-out when one event has multiple conversions
for cv in conversions:
ad_id = cv["ad_id"]
day = cv["conv_time"]
if ad_id not in valid_ad_ids or not in_window(day):
continue
bucket = metrics.setdefault(
(day, ad_id),
{"date": day, "ad_id": ad_id, "impressions": 0, "clicks": 0, "conversions": 0},
)
bucket["conversions"] += 1
# Compute rates and return rows sorted by (date, ad_id)
result = []
for key in sorted(metrics):
row = metrics[key]
row["ctr"] = row["clicks"] / row["impressions"] if row["impressions"] else 0.0
row["conversion_rate"] = row["conversions"] / row["clicks"] if row["clicks"] else 0.0
result.append(row)
return result