Weekly Cohort Activity Retention Analysis
SQL & DataAuto-graded · 20 test casesLast updated
Group users by signup week, compute seven-day activity retention rates, and handle zero-retention cohorts correctly.
Problem
You are analyzing user activity data stored in two tables:
users table:
user_id: unique identifier for each usersignup_date: timestamp when the user signed upplan_type: subscription plan type
events table:
user_id: identifier linking the event to a userevent_ts: timestamp when the event occurred
Your task is to compute retention metrics grouped by signup week cohorts.
Cohort Definition
A cohort is defined by the Monday-midnight start of the calendar week containing each user's signup_date. In this problem, weeks begin on Monday at 00:00:00. For example, any signup between Monday, January 1, 2024 00:00:00 and Sunday, January 7, 2024 23:59:59 belongs to the cohort with signup_week of 2024-01-01 00:00:00.
Retention Definition
A user is considered retained if they have at least one event in the time window starting at their signup_date (inclusive) and ending strictly before signup_date + 7 days. An event at exactly the signup timestamp counts as retained. An event at exactly seven days after signup does not count.
Requirements
Implement a function that takes two lists of dictionaries (representing the tables) and returns one dictionary per cohort with these fields, in this order:
signup_week: the Monday-midnight start timestamp of the cohort, formatted as'YYYY-MM-DD HH:MM:SS', orNonefor users with null signup datescohort_size: total number of distinct users in that cohortretained_users: number of distinct users in that cohort who had at least one qualifying eventretention_rate:retained_users / cohort_size, rounded to exactly 4 decimal places
Important Rules
- The cohort size includes all users in that week, even those with zero qualifying events
- A user with multiple qualifying events counts only once in
retained_users - Include cohorts where no users were retained (retention_rate = 0.0)
- Only include cohorts that actually have users; do not add empty calendar weeks
- Sort results by
signup_weekascending, withNonecohorts last - Users with
Nonesignup dates form a separate cohort but can never be retained (comparisons withNoneare always false) - Duplicate user_id entries: take the first occurrence only
Constraints
- 0 ≤ len(users) ≤ 100,000
- 0 ≤ len(events) ≤ 1,000,000
- Timestamps may be provided as
datetimeobjects,dateobjects, or ISO 8601 strings (with or without 'Z' suffix) - All timestamps should be treated as naive (timezone-unaware) for comparison purposes
- Round retention rates using ROUND_HALF_UP to 4 decimal places
Examples
Example 1
Input: compute_cohort_retention([{'user_id': 1, 'signup_date': '2024-01-01 10:00:00', 'plan_type': 'free'}, {'user_id': 2, 'signup_date': '2024-01-02 12:00:00', 'plan_type': 'pro'}, {'user_id': 3, 'signup_date': '2024-01-08 00:00:00', 'plan_type': 'free'}], [{'user_id': 1, 'event_ts': '2024-01-01 10:00:00'}, {'user_id': 1, 'event_ts': '2024-01-08 10:00:00'}, {'user_id': 2, 'event_ts': '2024-01-09 12:00:00'}, {'user_id': 3, 'event_ts': '2024-01-14 23:59:59'}])
Output: [{'signup_week': '2024-01-01 00:00:00', 'cohort_size': 2, 'retained_users': 1, 'retention_rate': 0.5}, {'signup_week': '2024-01-08 00:00:00', 'cohort_size': 1, 'retained_users': 1, 'retention_rate': 1}]
Example 2
Input: compute_cohort_retention([{'user_id': 10, 'signup_date': '2024-03-04', 'plan_type': 'free'}, {'user_id': 11, 'signup_date': '2024-03-05', 'plan_type': 'free'}, {'user_id': 12, 'signup_date': '2024-03-10', 'plan_type': 'pro'}], [])
Output: [{'signup_week': '2024-03-04 00:00:00', 'cohort_size': 3, 'retained_users': 0, 'retention_rate': 0}]
Hints
Hint 1
Start by grouping users into cohorts based on their signup week, then check retention for each user individually before aggregating.
Hint 2
Use a half-open interval [signup, signup + 7 days) to test whether each event qualifies. Be careful with boundary conditions.
Hint 3
Avoid joining users to events in a way that creates multiple rows per user, which would inflate your counts. Consider computing a boolean 'is_retained' flag per user first.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The key insight is to process data in stages: first determine each user's cohort and retention status individually, then aggregate by cohort. This avoids the common pitfall of joining users to events, which creates multiple rows per user and inflates counts.
Algorithm Steps
-
Parse and normalize timestamps: Convert all date/datetime inputs to naive datetime objects for consistent comparison.
-
Assign each user to a cohort: Compute the Monday-midnight start of the week containing each user's signup date. This becomes the cohort identifier. Handle duplicate user_id entries by keeping only the first occurrence.
-
Determine retention per user: For each user with a non-null signup date, check if any of their events fall in the half-open interval [signup_date, signup_date + 7 days). Store the set of retained user IDs. Users with null signup dates can never be retained because comparisons with None always fail.
-
Aggregate by cohort: For each cohort, count the total number of users (cohort_size) and the number of retained users. Compute the retention rate as retained_users / cohort_size, using Decimal arithmetic with ROUND_HALF_UP to get exactly 4 decimal places.
-
Sort and return: Order results by signup_week ascending, placing the None cohort (if any) at the end.
Why This Works
- Correct denominators: Every user appears exactly once in exactly one cohort, so cohort_size reflects all users regardless of activity.
- No double-counting: Each user is either retained or not retained. Multiple qualifying events don't inflate the retained_users count.
- Handles zero-retention cohorts: Cohorts are derived from the users table, so weeks with signups but no activity still appear in the output with retention_rate = 0.0.
- Precise time windows: The retention window is anchored to each user's individual signup timestamp, not the cohort start. A user signing up on Sunday gets a full seven-day window extending into the next calendar week.
Complexity
- Time: O(U + E + C log C) where U is the number of users, E is the number of events, and C is the number of cohorts. Grouping events by user is O(E). Checking retention for each user scans only that user's events, totaling O(E) across all users. Building cohorts is O(U), and sorting cohorts is O(C log C), which is typically much smaller than U.
- Space: O(U + E) to store user data, cohort mappings, and event groupings.
Implementation
from datetime import datetime, date, time, timedelta
from decimal import Decimal, ROUND_HALF_UP
from typing import List, Dict
def compute_cohort_retention(users: List[Dict], events: List[Dict]) -> List[Dict]:
def parse_ts(value):
if value is None:
return None
if isinstance(value, datetime):
return value.replace(tzinfo=None) if value.tzinfo is not None else value
if isinstance(value, date):
return datetime.combine(value, time.min)
s = str(value).strip()
if s.endswith('Z'):
s = s[:-1] + '+00:00'
dt = datetime.fromisoformat(s)
if dt.tzinfo is not None:
dt = dt.replace(tzinfo=None)
return dt
def week_start(dt):
if dt is None:
return None
monday = dt.date() - timedelta(days=dt.weekday())
return datetime.combine(monday, time.min)
def format_ts(dt):
return dt.isoformat(sep=' ') if dt is not None else None
user_by_id = {}
for user in users:
uid = user.get('user_id')
if uid not in user_by_id:
signup = parse_ts(user.get('signup_date'))
user_by_id[uid] = (signup, week_start(signup))
cohort_users = {}
for uid, (signup, cohort) in user_by_id.items():
cohort_users.setdefault(cohort, set()).add(uid)
qualifying_users = set()
event_times_by_user = {}
for event in events:
uid = event.get('user_id')
ts = parse_ts(event.get('event_ts'))
if ts is not None:
event_times_by_user.setdefault(uid, []).append(ts)
for uid, (signup, cohort) in user_by_id.items():
if signup is None:
continue
end = signup + timedelta(days=7)
if any(signup <= ts < end for ts in event_times_by_user.get(uid, [])):
qualifying_users.add(uid)
result = []
for cohort, identifiers in cohort_users.items():
size = len(identifiers)
retained = sum(1 for uid in identifiers if uid in qualifying_users)
rate = (Decimal(retained) / Decimal(size)).quantize(
Decimal('0.0001'), rounding=ROUND_HALF_UP
) if size else Decimal('0.0000')
result.append({
'signup_week': format_ts(cohort),
'cohort_size': size,
'retained_users': retained,
'retention_rate': float(rate)
})
result.sort(key=lambda row: (row['signup_week'] is None, row['signup_week'] or ''))
return result