Daily Active Users, New-User Cohorts and Next-Day Return Rate
SQL & DataAuto-graded · 14 test casesLast updated
Build a fixed 7-day report of active users, first-activity cohorts, next-day return rate and revenue per active user from raw logs, with bot filtering and deduplication.
You are given three raw tables as lists of rows, each row a list of strings (or None for missing values). Build a daily report for the fixed reporting window 2025-08-26 through 2025-09-01 (7 consecutive days, all times in UTC).
Input
accounts: rows[user_id, signup_date, country]. This table is provided for completeness and is not needed for any metric.activity: rows[user_id, event_time, event_type, product_id].event_timelooks like"2025-08-26 09:00:00", andproduct_idmay beNone.orders: rows[user_id, purchase_time, order_id, amount].purchase_timehas the same format asevent_time, andamountis a decimal string such as"9.99".
Preparation rules
- Bots. Ignore every row whose
user_idstarts with the literal prefixbot_(case-sensitive, the underscore is a normal character). Apply this toactivityandorders, so bots affect no metric. - Deduplication. In
activity, rows that are identical in all four fields count as a single event. Do not deduplicateorders. - Calendar day. The day of a timestamp is its first 10 characters (
YYYY-MM-DD), interpreted as a UTC date.
Metrics per day d in the window
dau: number of distinct users with at least one (cleaned) event on dayd.new_users: number of users whose earliest event day over the entire activity log (not just inside the window) is exactlyd. This depends only on events, never onsignup_date.d1_retention_rate: among thenew_usersof dayd, the fraction that also have at least one event on dayd + 1. The day after the window's last day (2025-09-02) is checked normally if events exist. Ifnew_usersis 0, the rate is0.0.revenue_per_dau: totalamountof non-bot purchases whose purchase day isd, divided bydau. Ifdauis 0, the value is0.0, even if revenue exists that day. Purchases are counted by their own timestamp and need not be tied to that user's activity.
Output
Return a list of exactly 7 dictionaries, ordered by day ascending, one for each day in the window (including days with no activity). Each dictionary has the keys:
"day": the ISO date string, e.g."2025-08-26""dau": int"new_users": int"d1_retention_rate": number"revenue_per_dau": number
Do not round the ratios.
Constraints
- The window is fixed: 2025-08-26 to 2025-09-01 inclusive.
- Row counts can be large enough that a single pass with hash-based sets is expected (no per-day rescans of all events).
- Timestamps are well-formed strings of the form
YYYY-MM-DD HH:MM:SS. amountvalues are non-negative decimal strings.- Events and purchases may fall outside the window. Events before the window matter for deciding who is "new". Purchases outside the window are ignored.
- User ids such as
botx9(no underscore afterbot) are not bots.
Examples
Example 1
Input: daily_cohort_report([['u1', '2025-08-25', 'US'], ['u2', '2025-08-26', 'US'], ['u3', '2025-08-26', 'IN'], ['u4', '2025-08-31', 'US'], ['u5', '2025-09-01', 'US'], ['bot_1', '2025-08-26', 'US']], [['u1', '2025-08-26 09:00:00', 'app_open', None], ['u1', '2025-08-27 10:00:00', 'app_open', None], ['u2', '2025-08-26 12:00:00', 'app_open', None], ['u2', '2025-08-27 13:00:00', 'view', 'P1'], ['u2', '2025-08-28 12:00:00', 'app_open', None], ['u3', '2025-08-26 15:00:00', 'app_open', None], ['u3', '2025-08-27 16:00:00', 'app_open', None], ['u4', '2025-09-01 08:00:00', 'app_open', None], ['u5', '2025-09-01 09:00:00', 'app_open', None], ['bot_1', '2025-08-26 10:00:00', 'app_open', None]], [['u1', '2025-08-27 11:00:00', 'o1', '9.99'], ['u2', '2025-08-28 11:30:00', 'o2', '4.00'], ['u3', '2025-08-29 14:00:00', 'o3', '2.50'], ['u4', '2025-09-01 09:30:00', 'o4', '1.00'], ['u5', '2025-09-02 10:00:00', 'o5', '5.00'], ['bot_1', '2025-08-26 10:30:00', 'o6', '100.00']])
Output: [{'day': '2025-08-26', 'dau': 3, 'new_users': 3, 'd1_retention_rate': 1, 'revenue_per_dau': 0}, {'day': '2025-08-27', 'dau': 3, 'new_users': 0, 'd1_retention_rate': 0, 'revenue_per_dau': 3.33}, {'day': '2025-08-28', 'dau': 1, 'new_users': 0, 'd1_retention_rate': 0, 'revenue_per_dau': 4}, {'day': '2025-08-29', 'dau': 0, 'new_users': 0, 'd1_retention_rate': 0, 'revenue_per_dau': 0}, {'day': '2025-08-30', 'dau': 0, 'new_users': 0, 'd1_retention_rate': 0, 'revenue_per_dau': 0}, {'day': '2025-08-31', 'dau': 0, 'new_users': 0, 'd1_retention_rate': 0, 'revenue_per_dau': 0}, {'day': '2025-09-01', 'dau': 2, 'new_users': 2, 'd1_retention_rate': 0, 'revenue_per_dau': 0.5}]
Hints
Hint 1
Reduce the cleaned events to a set of distinct (user, day) pairs first. DAU, first activity day and retention can all be derived from it.
Hint 2
A user's cohort day is the minimum day over all their events, including those before the window. Only users whose cohort day falls in the window count as new.
Hint 3
For retention, intersect the cohort set of day d with the set of active users on day d+1. Handle zero denominators explicitly by returning 0.0.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Each metric has its own grain, so compute the pieces independently and then assemble one row per calendar day of the fixed 7-day window. Every output day appears, even with no activity.
- Clean the events. Skip rows whose user id starts with
bot_, and put the remaining rows into a set of 4-tuples. This removes exact duplicates.Nonevalues hash and compare fine inside tuples. - Build user-day information. For each unique event, take the date from the first 10 characters of the timestamp. Add the user to
active_by_day[date], and keep the minimum date seen per user infirst_day. Becausefirst_dayuses all history, a user who first appeared before the window is never "new" inside it. - Cohorts. Group users by their first day, keeping only days inside the window.
- Revenue. Sum amounts of non-bot purchases by purchase date, for dates inside the window. Orders are not deduplicated and not linked to activity.
- Assemble. For each day
d:dauis the size ofactive_by_day[d].new_usersis the size of the cohort ford.- Retained users are
cohort[d] ∩ active_by_day[d+1]. The rate isretained / new_users, or0.0if the cohort is empty. revenue_per_dauisrevenue[d] / dau, or0.0ifdauis 0.
Why it is correct
- Sets of user ids make "distinct users" automatic, so DAU and retention cannot be inflated by repeated events.
- The first-day minimum is taken over every cleaned event, matching the "first-ever event" definition.
signup_dateis never consulted. - The retention check uses
active_by_dayford+1without a window restriction, so the last window day correctly looks at 2025-09-02. - Bot filtering happens at the source for both tables, and the explicit zero guards cover empty cohorts and zero-DAU days.
Complexity
- Time: O(E + P + 7), where E is the number of activity rows and P the number of order rows. Set operations per day are bounded by the size of that day's cohort.
- Space: O(E) for the deduplicated events and per-day user sets.
Reference solution
from datetime import date, timedelta
from collections import defaultdict
from typing import List, Dict
def daily_cohort_report(accounts: List[List[str]], activity: List[List[str]], orders: List[List[str]]) -> List[Dict]:
start = date(2025, 8, 26)
days = [start + timedelta(days=i) for i in range(7)]
day_set = set(days)
# Drop bots and exact duplicate event rows.
unique_events = set()
for row in activity:
if len(row) >= 4 and not str(row[0]).startswith("bot_"):
unique_events.add((row[0], row[1], row[2], row[3]))
# Active users per day and each user's first-ever active day.
active_by_day = defaultdict(set)
first_day = {}
for user_id, event_time, event_type, product_id in unique_events:
d = date.fromisoformat(str(event_time)[:10])
active_by_day[d].add(user_id)
if user_id not in first_day or d < first_day[user_id]:
first_day[user_id] = d
# Cohorts inside the window.
cohort_by_day = defaultdict(set)
for user_id, d in first_day.items():
if d in day_set:
cohort_by_day[d].add(user_id)
# Revenue per day (non-bot, inside the window, no dedupe).
revenue_by_day = defaultdict(float)
for row in orders:
if len(row) < 4:
continue
user_id, purchase_time, order_id, amount = row[:4]
if str(user_id).startswith("bot_"):
continue
d = date.fromisoformat(str(purchase_time)[:10])
if d in day_set:
revenue_by_day[d] += float(amount)
result = []
for d in days:
active = active_by_day.get(d, set())
cohort = cohort_by_day.get(d, set())
retained = cohort & active_by_day.get(d + timedelta(days=1), set())
dau = len(active)
new_count = len(cohort)
result.append({
"day": d.isoformat(),
"dau": dau,
"new_users": new_count,
"d1_retention_rate": (len(retained) / new_count) if new_count else 0.0,
"revenue_per_dau": (revenue_by_day.get(d, 0.0) / dau) if dau else 0.0,
})
return result