Audit Purchase Events Against a Payment Ledger
Arrays & HashingAuto-graded · 16 test casesLast updated
Aggregate daily purchase metrics from event logs and reconcile two event snapshots against a ledger to judge whether a tracking fix worked, using hash-map grouping.
A mobile game sells in-app purchases. Its analytics pipeline was broken and then patched. You are given the payment ledger, which is the trusted source of truth, and two snapshots of the purchase events the pipeline emitted: one from before the patch and one from after. Write a function that builds the daily report for each snapshot and checks how well each snapshot agrees with the ledger.
Inputs
All records are dictionaries.
daily_active: a list of{"day": str, "user": str}. Each entry says a user was active on a day. The same pair may appear more than once.ledger: a list of{"id": str, "user": str, "day": str, "amount": int}, the real purchases.amountis in cents.events_before: a list of purchase events with the same fields as ledger entries, emitted before the patch.events_after: the same, emitted after the patch.
If several ledger entries share an id, only the last one in list order counts. The ledger therefore holds one purchase per distinct id.
Part 1: Daily metrics
For each snapshot, build a dictionary keyed by day. The set of days included differs between the two reports:
- "before" report: every day that appears in
daily_activeor inevents_before. - "after" report: every day that appears in
daily_active, inevents_beforeor inevents_after. The after report keeps the whole reporting period, so a day that only had events in the before snapshot still appears, with zero purchases if the after snapshot has none for it.
Days that appear only in the ledger are never included. Each day maps to a dictionary with these keys, computed from that report's own snapshot:
dau: the number of distinct users indaily_activefor that day (0 if none).reported_purchases: the number of event rows for that day, duplicates included.reported_purchasers: the number of distinct users among that day's event rows.reported_revenue_cents: the sum ofamountover that day's event rows.conversion_rate:reported_purchasers / dau, or0ifdauis 0.arppu_cents:reported_revenue_cents / reported_purchasers, or0if there are no purchasers.
These metrics are computed from the events exactly as reported, with no correction against the ledger. Events are grouped by their own day field.
Part 2: Reconciliation
For each snapshot, compare its events with the ledger and compute:
actual_purchases: the number of distinct ledger ids.event_rows: the total number of event rows in the snapshot.- For each distinct ledger id, let
cbe the number of event rows carrying that id:c == 0: add 1 tomissing_purchases.c == 1: add 1 tomatched_events. Then compare that event with the ledger entry. If theamountdiffers, add 1 toamount_mismatches. If theuseror thedaydiffers (or both), add 1 toattribute_mismatches. This is a single increment even if both differ. The two checks are independent, so one event can raise both counters.c > 1: add 1 tomatched_eventsand addc - 1toduplicate_events. Fields of duplicated events are not compared.
extra_events: the number of event rows whoseiddoes not exist in the ledger. Each such row counts, including repeats of the same unknown id.error_score:missing_purchases + extra_events + duplicate_events + amount_mismatches + attribute_mismatches.repair_valid:Trueexactly whenerror_score == 0.
Output
Return a dictionary:
{
"before": <daily metrics for events_before>,
"after": <daily metrics for events_after>,
"validation": {
"before": <reconciliation dict for events_before>,
"after": <reconciliation dict for events_after>,
"improved": <True if after error_score < before error_score, else False>
}
}
Each reconciliation dictionary has the keys actual_purchases, event_rows, matched_events, missing_purchases, extra_events, duplicate_events, amount_mismatches, attribute_mismatches, error_score and repair_valid.
Constraints
- Up to about 10^5 records in each list.
amountis a non-negative integer number of cents.- Day strings are compared as plain strings. Output days are ordered by ascending string order, which is the same as chronological order for ISO dates.
- Any list may be empty.
Examples
Example 1
Input: audit_purchase_reporting([{'day': '2025-01-01', 'user': 'u1'}, {'day': '2025-01-01', 'user': 'u2'}, {'day': '2025-01-02', 'user': 'u1'}], [{'id': 't1', 'user': 'u1', 'day': '2025-01-01', 'amount': 499}, {'id': 't2', 'user': 'u2', 'day': '2025-01-01', 'amount': 999}, {'id': 't3', 'user': 'u1', 'day': '2025-01-02', 'amount': 499}], [{'id': 't1', 'user': 'u1', 'day': '2025-01-01', 'amount': 499}, {'id': 't2', 'user': 'u2', 'day': '2025-01-01', 'amount': 999}], [{'id': 't1', 'user': 'u1', 'day': '2025-01-01', 'amount': 499}, {'id': 't2', 'user': 'u2', 'day': '2025-01-01', 'amount': 999}, {'id': 't3', 'user': 'u1', 'day': '2025-01-02', 'amount': 499}])
Output: {'before': {'2025-01-01': {'dau': 2, 'reported_purchases': 2, 'reported_purchasers': 2, 'reported_revenue_cents': 1498, 'conversion_rate': 1, 'arppu_cents': 749}, '2025-01-02': {'dau': 1, 'reported_purchases': 0, 'reported_purchasers': 0, 'reported_revenue_cents': 0, 'conversion_rate': 0, 'arppu_cents': 0}}, 'after': {'2025-01-01': {'dau': 2, 'reported_purchases': 2, 'reported_purchasers': 2, 'reported_revenue_cents': 1498, 'conversion_rate': 1, 'arppu_cents': 749}, '2025-01-02': {'dau': 1, 'reported_purchases': 1, 'reported_purchasers': 1, 'reported_revenue_cents': 499, 'conversion_rate': 1, 'arppu_cents': 499}}, 'validation': {'before': {'actual_purchases': 3, 'event_rows': 2, 'matched_events': 2, 'missing_purchases': 1, 'extra_events': 0, 'duplicate_events': 0, 'amount_mismatches': 0, 'attribute_mismatches': 0, 'error_score': 1, 'repair_valid': False}, 'after': {'actual_purchases': 3, 'event_rows': 3, 'matched_events': 3, 'missing_purchases': 0, 'extra_events': 0, 'duplicate_events': 0, 'amount_mismatches': 0, 'attribute_mismatches': 0, 'error_score': 0, 'repair_valid': True}, 'improved': True}}
Example 2
Input: audit_purchase_reporting([{'day': '2025-02-01', 'user': 'a'}, {'day': '2025-02-01', 'user': 'b'}, {'day': '2025-02-01', 'user': 'b'}], [{'id': 'x', 'user': 'a', 'day': '2025-02-01', 'amount': 100}], [{'id': 'x', 'user': 'a', 'day': '2025-02-01', 'amount': 100}, {'id': 'x', 'user': 'a', 'day': '2025-02-01', 'amount': 100}, {'id': 'bad', 'user': 'b', 'day': '2025-02-01', 'amount': 50}], [{'id': 'x', 'user': 'a', 'day': '2025-02-01', 'amount': 100}])
Output: {'before': {'2025-02-01': {'dau': 2, 'reported_purchases': 3, 'reported_purchasers': 2, 'reported_revenue_cents': 250, 'conversion_rate': 1, 'arppu_cents': 125}}, 'after': {'2025-02-01': {'dau': 2, 'reported_purchases': 1, 'reported_purchasers': 1, 'reported_revenue_cents': 100, 'conversion_rate': 0.5, 'arppu_cents': 100}}, 'validation': {'before': {'actual_purchases': 1, 'event_rows': 3, 'matched_events': 1, 'missing_purchases': 0, 'extra_events': 1, 'duplicate_events': 1, 'amount_mismatches': 0, 'attribute_mismatches': 0, 'error_score': 2, 'repair_valid': False}, 'after': {'actual_purchases': 1, 'event_rows': 1, 'matched_events': 1, 'missing_purchases': 0, 'extra_events': 0, 'duplicate_events': 0, 'amount_mismatches': 0, 'attribute_mismatches': 0, 'error_score': 0, 'repair_valid': True}, 'improved': True}}
Example 3
Input: audit_purchase_reporting([{'day': '2025-03-01', 'user': 'p1'}], [], [], [])
Output: {'before': {'2025-03-01': {'dau': 1, 'reported_purchases': 0, 'reported_purchasers': 0, 'reported_revenue_cents': 0, 'conversion_rate': 0, 'arppu_cents': 0}}, 'after': {'2025-03-01': {'dau': 1, 'reported_purchases': 0, 'reported_purchasers': 0, 'reported_revenue_cents': 0, 'conversion_rate': 0, 'arppu_cents': 0}}, 'validation': {'before': {'actual_purchases': 0, 'event_rows': 0, 'matched_events': 0, 'missing_purchases': 0, 'extra_events': 0, 'duplicate_events': 0, 'amount_mismatches': 0, 'attribute_mismatches': 0, 'error_score': 0, 'repair_valid': True}, 'after': {'actual_purchases': 0, 'event_rows': 0, 'matched_events': 0, 'missing_purchases': 0, 'extra_events': 0, 'duplicate_events': 0, 'amount_mismatches': 0, 'attribute_mismatches': 0, 'error_score': 0, 'repair_valid': True}, 'improved': False}}
Hints
Hint 1
Group by day with dictionaries of sets and lists: one for distinct active users, one for event rows per snapshot. Decide the set of days for each report before computing anything, and remember the after report also covers days seen in the before events.
Hint 2
Index each snapshot by event id, mapping id to the list of rows with that id. Then every ledger id can be classified as missing (0 rows), single (1 row, so compare fields) or duplicated (more than 1 row) in constant time.
Hint 3
Extra events are counted per row, not per distinct id. Duplicate counts only apply to ids that exist in the ledger. Guard both divisions against a zero denominator.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The task has two independent parts that use the same hash-map grouping idea.
Daily metrics. Collect distinct active users per day in a map of sets. Group each snapshot's events by day. Choose the day set for each report:
- The before report uses the days from
daily_activeandevents_before. - The after report uses the days from
daily_active,events_beforeandevents_after.
For every day in the chosen set, taken in sorted order, compute the row count, the distinct purchaser count and the revenue sum from that report's own events. Derive conversion and ARPPU, guarding each division against a zero denominator.
Reconciliation. Collapse the ledger into a dictionary keyed by id. Later entries overwrite earlier ones, which gives the "last wins" rule. Group the snapshot's events by id. Then:
- Walk the ledger ids. Zero event rows means the purchase is missing. Exactly one row means it is matched, and its amount and its user/day are compared separately. More than one row means it is matched, and the surplus rows are duplicates.
- Walk the event rows once more and count those whose id is not in the ledger as extra events.
- Sum the five discrepancy counters into
error_score. The repair is valid only when that score is 0.
Finally, improved is true when the after-snapshot error score is strictly lower than the before-snapshot score.
Why it is correct
Every ledger id falls into exactly one of three cases (0, 1 or more than 1 rows), so each discrepancy is counted once. Phantom events are exactly the rows whose id is absent from the ledger, so they cannot overlap with the ledger-driven counts. Metrics use only the reported events, so they show what the broken or fixed pipeline would publish, while the reconciliation shows how far that output is from the truth. Using the wider day set for the after report keeps days that only had before-snapshot events visible, now showing zeros if the fix removed them.
Complexity
Let N be the total number of records. Grouping and lookups are O(N) with hashing. Sorting the days adds O(D log D), where D is the number of distinct days. Space is O(N).
Reference solution
from typing import List, Dict
from collections import defaultdict
def audit_purchase_reporting(daily_active: List[Dict], ledger: List[Dict], events_before: List[Dict], events_after: List[Dict]) -> Dict:
users_by_day = defaultdict(set)
for rec in daily_active:
users_by_day[rec['day']].add(rec['user'])
ledger_by_id = {t['id']: t for t in ledger}
def daily_metrics(events, days):
events_by_day = defaultdict(list)
for e in events:
events_by_day[e['day']].append(e)
result = {}
for day in sorted(days):
dau = len(users_by_day[day]) if day in users_by_day else 0
rows = events_by_day.get(day, [])
purchases = len(rows)
purchasers = len(set(e['user'] for e in rows))
revenue = sum(e['amount'] for e in rows)
conversion = purchasers / dau if dau > 0 else 0
arppu = revenue / purchasers if purchasers > 0 else 0
result[day] = {
'dau': dau,
'reported_purchases': purchases,
'reported_purchasers': purchasers,
'reported_revenue_cents': revenue,
'conversion_rate': conversion,
'arppu_cents': arppu,
}
return result
def reconcile(events):
rows_by_id = defaultdict(list)
for e in events:
rows_by_id[e['id']].append(e)
matched = missing = extra = duplicates = 0
amount_mismatches = attribute_mismatches = 0
for tid, txn in ledger_by_id.items():
rows = rows_by_id.get(tid, [])
c = len(rows)
if c == 0:
missing += 1
elif c == 1:
ev = rows[0]
if ev['amount'] != txn['amount']:
amount_mismatches += 1
if ev['user'] != txn['user'] or ev['day'] != txn['day']:
attribute_mismatches += 1
matched += 1
else:
duplicates += c - 1
matched += 1
for e in events:
if e['id'] not in ledger_by_id:
extra += 1
error_score = missing + extra + duplicates + amount_mismatches + attribute_mismatches
return {
'actual_purchases': len(ledger_by_id),
'event_rows': len(events),
'matched_events': matched,
'missing_purchases': missing,
'extra_events': extra,
'duplicate_events': duplicates,
'amount_mismatches': amount_mismatches,
'attribute_mismatches': attribute_mismatches,
'error_score': error_score,
'repair_valid': error_score == 0,
}
active_days = set(users_by_day.keys())
before_days_only = set(e['day'] for e in events_before)
after_days_only = set(e['day'] for e in events_after)
before_days = active_days | before_days_only
after_days = active_days | before_days_only | after_days_only
before_metrics = daily_metrics(events_before, before_days)
after_metrics = daily_metrics(events_after, after_days)
before_val = reconcile(events_before)
after_val = reconcile(events_after)
return {
'before': before_metrics,
'after': after_metrics,
'validation': {
'before': before_val,
'after': after_val,
'improved': after_val['error_score'] < before_val['error_score'],
},
}