Seven-Day Retention Rates by Weekly Cohort
Medium · Data Manipulation (SQL/Python) · Data Scientist · Technical Screen
Problem Statement
You are analyzing product engagement across two datasets:
users: account records withuser_id(unique identifier),signup_date(registration date or timestamp), andplan_type(subscription tier).events: activity records withuser_id(account identifier) andevent_ts(activity timestamp).
Bucket accounts into weekly registration cohorts defined by the ISO calendar week of signup_date, where every week begins on Monday at 00:00:00 (signup_week).
An account counts as retained in week one if at least one events record with the same user_id falls inside the half-open window [signup_date, signup_date + 7 days)—meaning event_ts >= signup_date and event_ts < signup_date + 7 days. Activity at the exact registration timestamp qualifies, whereas activity at signup_date + 7 days (or before signup_date) does not.
Implement:
def calculate_first_week_retention(users: List[Dict], events: List[Dict]) -> List[Dict]:
(In PostgreSQL, write a single read-only SELECT query producing the equivalent result table.)
Return one summary dictionary (or row) per weekly cohort present in users, containing these four fields in order:
signup_week: Monday00:00:00timestamp formatted as'YYYY-MM-DD HH:MM:SS'(orNone/NULLifsignup_dateis missing).cohort_size: count of distinct non-nulluser_idvalues belonging to that cohort, whether or not they logged qualifying activity.retained_users: count of distinctuser_idvalues in that cohort with at least one qualifying first-week event (multiple qualifying events for one user still count once).retention_rate:retained_users / cohort_sizerounded half-up to4decimal places (None/NULLifcohort_size == 0).
Keep cohorts whose retained_users is 0, but do not fabricate rows for calendar weeks that have zero records in users. Sort the output by signup_week ascending, placing any None (NULL) cohort row last.
Examples
Example 1
Input:
users = [
{"user_id": 101, "signup_date": "2025-04-07 08:30:00", "plan_type": "starter"},
{"user_id": 102, "signup_date": "2025-04-09 15:00:00", "plan_type": "team"},
{"user_id": 103, "signup_date": "2025-04-13 22:00:00", "plan_type": "starter"},
{"user_id": 104, "signup_date": "2025-04-14 09:00:00", "plan_type": "team"},
]
events = [
{"user_id": 101, "event_ts": "2025-04-07 08:30:00"},
{"user_id": 101, "event_ts": "2025-04-10 12:00:00"},
{"user_id": 102, "event_ts": "2025-04-16 15:00:00"},
{"user_id": 103, "event_ts": "2025-04-20 21:59:59"},
{"user_id": 104, "event_ts": "2025-04-14 08:59:59"},
{"user_id": 999, "event_ts": "2025-04-08 10:00:00"},
]
Output:
[
{"signup_week": "2025-04-07 00:00:00", "cohort_size": 3, "retained_users": 2, "retention_rate": 0.6667},
{"signup_week": "2025-04-14 00:00:00", "cohort_size": 1, "retained_users": 0, "retention_rate": 0.0},
]
Explanation:
- Users 101 (Mon Apr 7), 102 (Wed Apr 9), and 103 (Sun Apr 13) belong to Monday cohort '2025-04-07 00:00:00' (cohort_size = 3). User 101 qualifies via two in-window events (counted once), 102's sole event lands at the excluded +7 days endpoint, and 103 qualifies 1 second before +7 days, giving 2 / 3 = 0.6667.
- User 104 starts Monday cohort '2025-04-14 00:00:00'; their only event is 1 second before signup, leaving 0 / 1 = 0.0. Event 999 has no matching users record and is ignored.
Example 2
Input:
users = [
{"user_id": "acct_1", "signup_date": "2025-06-02", "plan_type": "basic"},
{"user_id": "acct_2", "signup_date": "2025-06-06", "plan_type": "pro"},
{"user_id": "acct_3", "signup_date": "2025-06-18", "plan_type": "pro"},
]
events = [
{"user_id": "acct_2", "event_ts": "2025-06-08 18:00:00"},
]
Output:
[
{"signup_week": "2025-06-02 00:00:00", "cohort_size": 2, "retained_users": 1, "retention_rate": 0.5},
{"signup_week": "2025-06-16 00:00:00", "cohort_size": 1, "retained_users": 0, "retention_rate": 0.0},
]
Explanation: Bare date strings represent 00:00:00 midnight. Cohort '2025-06-02 00:00:00' retains acct_2 (1 / 2 = 0.5). The empty week '2025-06-09 00:00:00' is skipped because nobody registered that week, whereas '2025-06-16 00:00:00' appears with retention_rate = 0.0.
Constraints
- Timestamp strings use
'YYYY-MM-DD','YYYY-MM-DD HH:MM:SS', or'YYYY-MM-DDTHH:MM:SS'(orNone/NULL). usersandeventscan be empty, contain duplicate user records, or include events for unregistered IDs.- Missing (
None/NULL) identifiers or timestamps never satisfy join or window comparisons, matching SQL three-valued logic. - Rates round half-up to
4decimal places (matching PostgreSQLROUND(numeric, 4)).
Step-by-step walkthrough
Understand the cohorts, window, and output rules
We are given two tables—
users(user_id,signup_date,plan_type) andevents(user_id,event_ts)—and asked to compute first-week retention grouped by signup cohort (the group of users who signed up during the same Monday-through-Sunday calendar week).In the Python judge, both tables arrive as lists of dictionaries, and we return a list of dictionaries with keys
signup_week,cohort_size,retained_users, andretention_rate.The trickiest part of retention problems is getting every boundary rule exact:
- Personal half-open 7-day window
[signup_date, signup_date + 7 days): A half-open interval includes its start endpoint (>=) and excludes its end endpoint (<). Notice that the window is measured from each user's exactsignup_datetimestamp, not from Monday midnight:
Timeline for a user signing up at 2024-01-02 12:00:00: 2024-01-02 2024-01-02 2024-01-09 2024-01-09 11:59:59 12:00:00 11:59:59 12:00:00 -----|================[=============================]----------------|-----> OUT IN IN OUT (before) (exact signup) (7d minus 1s) (exact +7 days)- Distinct user counts: Both
cohort_sizeandretained_userscount distinctuser_idvalues. A user with five qualifying events—or a duplicate row inusers—still counts once. - Zero-retention cohorts stay; empty calendar weeks do not: Every signup week present in
usersgets a row (even ifretained_users == 0), while calendar weeks with zero signups are omitted. - Rounding and ordering:
retention_rateisretained_users / cohort_sizerounded half-up to 4 decimals. Rows are ordered bysignup_weekascending, with anyNone(NULL) signup week placed last.
- Personal half-open 7-day window
Write the PostgreSQL query first
Because the problem asks for one read-only PostgreSQL query and our Python code must mirror SQL semantics down to
NULLs and rounding, let us write the SQL query first and inspect each clause:SELECT -- Truncate each user's signup timestamp back to Monday 00:00:00 of that ISO week. DATE_TRUNC('week', u.signup_date) AS signup_week, COUNT(DISTINCT u.user_id) AS cohort_size, -- Unmatched LEFT JOIN rows have e.user_id = NULL, which COUNT(DISTINCT ...) ignores. COUNT(DISTINCT e.user_id) AS retained_users, -- Cast to numeric to avoid integer division; NULLIF prevents division by zero. ROUND( COUNT(DISTINCT e.user_id)::numeric / NULLIF(COUNT(DISTINCT u.user_id), 0), 4 ) AS retention_rate FROM users AS u -- Keep ALL users in the denominator; put the 7-day window check inside ON, not WHERE! LEFT JOIN events AS e ON e.user_id = u.user_id AND e.event_ts >= u.signup_date AND e.event_ts < u.signup_date + INTERVAL '7 days' GROUP BY DATE_TRUNC('week', u.signup_date) ORDER BY signup_week ASC NULLS LAST;Why must
e.event_ts >= u.signup_date AND e.event_ts < u.signup_date + INTERVAL '7 days'sit insideONrather thanWHERE? In aLEFT JOIN, anONcondition decides which events attach to a user: if a user has no qualifying events, the user still survives withe.user_id = NULL, keepingcohort_sizeaccurate and preserving0%-retention cohorts. Moving that check toWHEREwould filter out theNULLrows after the join, silently turning theLEFT JOINinto anINNER JOINand making every surviving cohort look100%retained!Why naive nested loops are slow, and how indexing fixes it
In Python, a naive translation loops through every user in
usersand, inside that loop, scans every row ineventslooking for a matchinguser_idand timestamp. Ifusershas50,000rows andeventshas500,000rows, that performs25,000,000,000comparisons (O(U * E)).Almost all of those comparisons check events belonging to completely different users! Instead, we do one pass over
eventsfirst to build a dictionaryevents_by_usermapping eachuser_idto a list of that user's event timestamps. Then each user only inspects their own events, dropping total work toO(U + E)—just like a database hash join.Parse timestamps and snap signups to Monday midnight
Input timestamps can arrive as bare dates (
'2024-03-04'), space-separated timestamps ('2024-01-01 10:00:00'),'T'-separated ISO strings, orNone. Python'sdatetime.fromisoformatparses all three text formats intodatetimeobjects (treating a bare date as00:00:00midnight).To find Monday
00:00:00ofts's week, we usets.weekday(), which numbersMonday = 0, Tuesday = 1, ..., Sunday = 6. Subtractingts.weekday()days fromts.date()always lands on the Monday that started that week—even across month or year boundaries:Signup timestamp ts.weekday() Subtract weekday() days signup_week --------------------------------------------------------------------------------------- 2024-01-01 10:00 (Mon) 0 2024-01-01 - 0 days -> 2024-01-01 00:00:00 2024-01-07 23:59 (Sun) 6 2024-01-07 - 6 days -> 2024-01-01 00:00:00 2024-01-08 00:00 (Mon) 0 2024-01-08 - 0 days -> 2024-01-08 00:00:00 2025-01-01 12:00 (Wed) 2 2025-01-01 - 2 days -> 2024-12-30 00:00:00from typing import Optional from datetime import datetime, timedelta FIRST_WEEK_WINDOW = timedelta(days=7) def parse_ts(value: Optional[str]) -> Optional[datetime]: """Parse 'YYYY-MM-DD', 'YYYY-MM-DD HH:MM:SS', or 'YYYY-MM-DDTHH:MM:SS' into a datetime.""" if value is None: return None return datetime.fromisoformat(value) def monday_week_start(ts: datetime) -> datetime: """Return Monday 00:00:00 of the calendar week containing ts.""" # ts.weekday() is 0 on Monday through 6 on Sunday, so subtracting it steps back to Monday. monday_date = ts.date() - timedelta(days=ts.weekday()) return datetime(monday_date.year, monday_date.month, monday_date.day)Check the 7-day window and match SQL half-up rounding
Next we write two small helpers:
has_qualifying_event(signup_ts, user_event_times)checks whether any of a user's events falls inside[signup_ts, signup_ts + 7 days). Ifsignup_tsisNone, the window is unknown (just asevent_ts >= NULLis unknown in SQL), so it returnsFalse.round_half_up(numerator, denominator, digits)matches SQL'sROUND(numeric, 4). Why not call Python's built-inround(retained / size, 4)? Because Python uses round-half-to-even (banker's rounding), whereas SQLROUNDon exactnumericvalues rounds halves up! For1retained user out of32,1 / 32 = 0.03125sits halfway between0.0312and0.0313: Python'sround(1 / 32, 4)gives0.0312, while PostgreSQL gives0.0313.
We avoid floating-point inaccuracies completely with exact integer arithmetic. Adding
1/2before flooringx = (numerator * 10^4) / denominatoris the same as(2 * numerator * 10^4 + denominator) // (2 * denominator): - For1 / 32at4digits (scale = 10000):(2 * 1 * 10000 + 32) // (2 * 32) = 20032 // 64 = 313, and313 / 10000 = 0.0313.from typing import List, Optional from datetime import datetime def round_half_up(numerator: int, denominator: int, digits: int) -> float: """Compute numerator / denominator rounded half-up to `digits` decimals, matching SQL ROUND.""" scale = 10 ** digits rounded_scaled = (2 * numerator * scale + denominator) // (2 * denominator) return rounded_scaled / scale def has_qualifying_event(signup_ts: Optional[datetime], user_event_times: List[datetime]) -> bool: """Return True if at least one event falls in the half-open window [signup_ts, signup_ts + 7 days).""" if signup_ts is None: return False window_end = signup_ts + FIRST_WEEK_WINDOW for event_ts in user_event_times: # Inclusive at signup_ts (>=) and strictly exclusive 7 days later (<). if signup_ts <= event_ts < window_end: return True return FalseGroup users into cohorts, sort weeks, and build output rows
Now we assemble
calculate_first_week_retentionin four clean phases matching the SQL query:- Index events (
events_by_user): Skip events withNoneuser ID or timestamp, since SQLNULLs never match inON. - Populate per-cohort sets (
cohort_users,cohort_retained): Usingsets automatically handlesCOUNT(DISTINCT ...)when a user has multiple events or duplicate rows inusers. Notice we initializecohort_users[week_key]before skippinguser_id is None, matching SQLGROUP BY+COUNT(DISTINCT u.user_id). - Order cohorts (
ordered_weeks): Sort all non-Noneweekdatetimekeys ascending, then appendNoneat the end (NULLS LAST). - Format rows (
output_rows): Convert each Mondaydatetimeto'YYYY-MM-DD %H:%M:%S'('YYYY-MM-DD 00:00:00') and computeretention_ratewhencohort_size > 0.
from typing import Any, Dict, List, Optional, Set from datetime import datetime def calculate_first_week_retention(users: List[Dict], events: List[Dict]) -> List[Dict]: events_by_user: Dict[Any, List[datetime]] = {} for event in events: user_id = event["user_id"] event_ts = parse_ts(event["event_ts"]) if user_id is None or event_ts is None: continue if user_id not in events_by_user: events_by_user[user_id] = [] events_by_user[user_id].append(event_ts) cohort_users: Dict[Optional[datetime], Set[Any]] = {} cohort_retained: Dict[Optional[datetime], Set[Any]] = {} for user in users: user_id = user["user_id"] signup_ts = parse_ts(user["signup_date"]) week_key = None if signup_ts is None else monday_week_start(signup_ts) if week_key not in cohort_users: cohort_users[week_key] = set() cohort_retained[week_key] = set() if user_id is None: continue cohort_users[week_key].add(user_id) user_events = events_by_user.get(user_id, []) if has_qualifying_event(signup_ts, user_events): cohort_retained[week_key].add(user_id) ordered_weeks: List[Optional[datetime]] = [] for week_key in cohort_users: if week_key is not None: ordered_weeks.append(week_key) ordered_weeks.sort() if None in cohort_users: ordered_weeks.append(None) output_rows: List[Dict] = [] for week_key in ordered_weeks: cohort_size = len(cohort_users[week_key]) retained_users = len(cohort_retained[week_key]) retention_rate = None if cohort_size > 0: retention_rate = round_half_up(retained_users, cohort_size, 4) week_label = None if week_key is None else week_key.strftime("%Y-%m-%d %H:%M:%S") output_rows.append({ "signup_week": week_label, "cohort_size": cohort_size, "retained_users": retained_users, "retention_rate": retention_rate, }) return output_rows- Index events (
Trace Example 1 step by step
Let us trace Example 1 (
2025-04-07and2025-04-14are both Mondays):User signup_date signup_week Window [signup, signup + 7d) User's events Retained? --------------------------------------------------------------------------------------------------------------------------- 101 2025-04-07 08:30:00 2025-04-07 00:00:00 [04-07 08:30:00, 04-14 08:30:00) 04-07 08:30:00 (IN) Yes 04-10 12:00:00 (IN) 102 2025-04-09 15:00:00 2025-04-07 00:00:00 [04-09 15:00:00, 04-16 15:00:00) 04-16 15:00:00 (OUT, +7d) No 103 2025-04-13 22:00:00 2025-04-07 00:00:00 [04-13 22:00:00, 04-20 22:00:00) 04-20 21:59:59 (IN) Yes 104 2025-04-14 09:00:00 2025-04-14 00:00:00 [04-14 09:00:00, 04-21 09:00:00) 04-14 08:59:59 (OUT, -1s) NoEvent
999never appears inusers, so it is ignored. Aggregating bysignup_week: -'2025-04-07 00:00:00':cohort_users = {101, 102, 103}(size = 3),cohort_retained = {101, 103}(retained = 2),rate = 0.6667. -'2025-04-14 00:00:00':cohort_users = {104}(size = 1),cohort_retained = set()(retained = 0),rate = 0.0.Complete solution
from typing import Any, Dict, List, Optional, Set, Tuple from datetime import datetime, timedelta FIRST_WEEK_WINDOW = timedelta(days=7) def parse_ts(value: Optional[str]) -> Optional[datetime]: """Parse 'YYYY-MM-DD', 'YYYY-MM-DD HH:MM:SS', or 'YYYY-MM-DDTHH:MM:SS' into a datetime.""" if value is None: return None return datetime.fromisoformat(value) def monday_week_start(ts: datetime) -> datetime: """Return Monday 00:00:00 of the calendar week containing ts.""" # ts.weekday() is 0 on Monday through 6 on Sunday, so subtracting it steps back to Monday. monday_date = ts.date() - timedelta(days=ts.weekday()) return datetime(monday_date.year, monday_date.month, monday_date.day) def round_half_up(numerator: int, denominator: int, digits: int) -> float: """Compute numerator / denominator rounded half-up to `digits` decimals, matching SQL ROUND.""" # Python's built-in round() uses round-half-to-even (1/32 = 0.03125 -> 0.0312), # whereas SQL ROUND(numeric, 4) rounds halves up (0.03125 -> 0.0313). # Exact integer identity: floor((numerator * scale) / denominator + 1/2) # = (2 * numerator * scale + denominator) // (2 * denominator). scale = 10 ** digits rounded_scaled = (2 * numerator * scale + denominator) // (2 * denominator) return rounded_scaled / scale def has_qualifying_event(signup_ts: Optional[datetime], user_event_times: List[datetime]) -> bool: """Return True if at least one event falls in the half-open window [signup_ts, signup_ts + 7 days).""" if signup_ts is None: return False window_end = signup_ts + FIRST_WEEK_WINDOW for event_ts in user_event_times: # Inclusive at signup_ts (>=) and strictly exclusive 7 days later (<). if signup_ts <= event_ts < window_end: return True return False def calculate_first_week_retention(users: List[Dict], events: List[Dict]) -> List[Dict]: # Phase 1: Index valid events by user_id for fast lookup (equivalent to a SQL hash join). # events_by_user: maps user_id -> list of event datetimes, e.g. {1: [datetime(2024, 1, 1, 10, 0)]}. events_by_user: Dict[Any, List[datetime]] = {} for event in events: user_id = event["user_id"] event_ts = parse_ts(event["event_ts"]) # Events missing user_id or event_ts behave like SQL NULLs and can never satisfy the join. if user_id is None or event_ts is None: continue if user_id not in events_by_user: events_by_user[user_id] = [] events_by_user[user_id].append(event_ts) # Phase 2: Bucket users into Monday signup-week cohorts and record distinct retained users. # cohort_users: maps week_key (Monday datetime or None) -> set of distinct user_ids. # cohort_retained: maps week_key (Monday datetime or None) -> set of distinct retained user_ids. cohort_users: Dict[Optional[datetime], Set[Any]] = {} cohort_retained: Dict[Optional[datetime], Set[Any]] = {} for user in users: user_id = user["user_id"] signup_ts = parse_ts(user["signup_date"]) week_key = None if signup_ts is None else monday_week_start(signup_ts) # Create the cohort entry before checking user_id so 0-user or 0-retention cohorts still appear. if week_key not in cohort_users: cohort_users[week_key] = set() cohort_retained[week_key] = set() # SQL COUNT(DISTINCT user_id) ignores NULL user_ids while preserving the GROUP BY row. if user_id is None: continue cohort_users[week_key].add(user_id) user_events = events_by_user.get(user_id, []) if has_qualifying_event(signup_ts, user_events): cohort_retained[week_key].add(user_id) # Phase 3: Sort real week datetimes ascending and place any None (NULL) week last. ordered_weeks: List[Optional[datetime]] = [] for week_key in cohort_users: if week_key is not None: ordered_weeks.append(week_key) ordered_weeks.sort() if None in cohort_users: ordered_weeks.append(None) # Phase 4: Format each cohort row with exact column names and 4-decimal SQL rounding. output_rows: List[Dict] = [] for week_key in ordered_weeks: cohort_size = len(cohort_users[week_key]) retained_users = len(cohort_retained[week_key]) retention_rate = None if cohort_size > 0: retention_rate = round_half_up(retained_users, cohort_size, 4) week_label = None if week_key is None else week_key.strftime("%Y-%m-%d %H:%M:%S") output_rows.append({ "signup_week": week_label, "cohort_size": cohort_size, "retained_users": retained_users, "retention_rate": retention_rate, }) return output_rows✅ Submit now — all tests should pass.
Intuition & how it works
Think of each calendar week's new signups as a freshman class—called a signup cohort (a group of users bucketed together by the Monday 00:00:00 of the week they joined). The moment a user signs up, they receive a personal 168-hour (7-day) pass covering the half-open interval [signup_date, signup_date + 7 days) (an interval that includes its start timestamp and stops just before its end timestamp). If a user logs at least one event while their pass is active, we check their name off on that class's "retained" roster, and each class's retention rate is (unique retained users) / (unique enrolled users).
A naive SQL query that uses an INNER JOIN—or uses a LEFT JOIN (which keeps unmatched left-table rows with NULLs on the right) but puts the 7-day filter in WHERE—discards every user who had zero qualifying events, shrinking the denominator so every cohort falsely reports 100% retention and 0%-retention cohorts vanish completely. In Python, scanning the entire events list for every user takes slow O(U * E) nested loops, and calling built-in round() applies banker's rounding (rounding exact .5 halves to the nearest even digit) instead of SQL's round-half-up rule (0.03125 -> 0.0313). Indexing events by user_id into a dictionary first and using sets of user IDs per cohort gives exact, fast results.
Walk through Example 1's four registered accounts:
- User 101 signs up Monday 2025-04-07 08:30:00 (cohort 2025-04-07 00:00:00). Events at 04-07 08:30:00 (exact signup, counts!) and 04-10 12:00:00 (3 days later, deduplicated) -> retained.
- User 102 signs up Wednesday 2025-04-09 15:00:00 (same cohort 2025-04-07 00:00:00). Only event is 04-16 15:00:00 (exact +7 days, excluded) -> not retained.
- User 103 signs up Sunday 2025-04-13 22:00:00 (still cohort 2025-04-07 00:00:00). Event at 04-20 21:59:59 (1 second before +7 days, counts!) -> retained, so the 2025-04-07 cohort reports 2 / 3 = 0.6667.
- User 104 signs up Monday 2025-04-14 09:00:00 (new cohort 2025-04-14 00:00:00). Event at 04-14 08:59:59 (1 second early, excluded) -> not retained, keeping the cohort row with 0 / 1 = 0.0.
Complexity
Let U be the number of rows in users, E be the number of rows in events, and C be the number of distinct signup-week cohorts (C <= U).
- Time:
O(U + E + C log C)when eachuser_idappears once inusers. We scan allEevents once to group them intoevents_by_user, scan theUusers once where each user checks only their own list of events (summing to at mostEchecks overall), and sort theCcohort week keys inO(C log C)time. - Space:
O(U + E)becauseevents_by_userstores up toEparsed timestamps and thecohort_users/cohort_retainedsets store up toUdistinct user IDs across cohorts. - SQL scaling: Adding a composite B-tree index (a sorted two-column lookup structure) on
events(user_id, event_ts)lets PostgreSQL check each user's[signup_date, signup_date + 7 days)window via a fast range probe rather than scanning the entireeventstable.
Edge cases
- Exact window endpoints: An event at
event_ts == signup_datecounts (>=), whereas an event atevent_ts == signup_date + 7 daysor1second beforesignup_datedoes not. - Monday/Sunday and New Year week boundaries:
2024-01-07 23:59:59(Sunday night) belongs to Monday2024-01-01 00:00:00,2024-01-08 00:00:00starts a new cohort, and Wednesday2025-01-01snaps back across New Year to Monday2024-12-30 00:00:00. - Zero-retention cohorts vs empty calendar weeks: A cohort whose users have zero qualifying events still outputs
retained_users = 0, retention_rate = 0.0, while calendar weeks with zero signups inusersare skipped. - Multiple events or duplicate user rows: Sets in Python (and
COUNT(DISTINCT ...)in SQL) guarantee eachuser_idcontributes at most1tocohort_sizeand at most1toretained_users. - Orphan events: Events whose
user_idnever appears inusersare ignored because cohorts come exclusively fromusers. NULL/Nonetimestamps or user IDs: Users withsignup_date = Noneform a singleNonecohort placed last (NULLS LAST) with0retained users; rows withuser_id = Nonestill create their cohort group if needed, without inflatingCOUNT(DISTINCT user_id).- Empty
userstable: Produces[](zero cohort rows).
Common mistakes
- Putting the 7-day event filter in
WHEREinstead ofLEFT JOIN ... ON: FilteringWHERE e.event_ts >= u.signup_datedrops unmatchedNULLrows, removing unretained users fromcohort_sizeand hiding zero-retention cohorts. - Forgetting
DISTINCTinCOUNT(e.user_id): A single active user who triggers 10 events in week 1 gets counted 10 times, pushingretention_rateabove1.0! - Using
<=instead of<at+ 7 days: Includes the 8th-day boundary instant (signup_date + 7 days), which fails Example 1 (User 102). - Truncating timestamps to calendar dates (
event_ts::date < signup_date::date + 7): Snaps a12:00afternoon signup back to00:00, mistakenly counting pre-signup morning events on day 0 and dropping valid morning events on day 7. - Starting weeks on Sunday: Functions like
strftime('%U')start weeks on Sunday instead of PostgreSQL's ISO Monday. - Integer division or Python
round(): WritingCOUNT(...) / COUNT(...)without::numerictruncates fractions to0in SQL, and Python'sround(1 / 32, 4)returns0.0312instead of SQL's0.0313.
Alternative approaches
- Pre-flagging each user with
EXISTSin a CTE: A Common Table Expression (CTE) is a named temporary subquery introduced withWITH. CheckingEXISTS (SELECT 1 FROM events e WHERE e.user_id = u.user_id AND e.event_ts >= u.signup_date AND e.event_ts < u.signup_date + INTERVAL '7 days')inside a CTE avoids row multiplication when active users have thousands of events, and still keeps every user in the cohort denominator. - Sorting per-user events + binary search in Python: If duplicate
user_idrows were very common inusers, sorting each user's event list once and callingbisect_left(user_events, signup_ts)would check each[signup_ts, signup_ts + 7 days)window inO(log k)time instead of scanning allkevents of that user.
Follow-up questions
- How do you avoid understating retention for the newest cohort when users signed up fewer than seven days before the snapshot cutoff? Those recent signups suffer from right-censoring—their 7-day observation window has not finished closing yet, so accounts that have not returned today might still log an event tomorrow and artificially depress the latest cohort's rate. Restrict
usersto mature signups withWHERE u.signup_date + INTERVAL '7 days' <= <snapshot_cutoff_ts>(filtering onuserspreserves theLEFT JOIN), or mark the incomplete trailing week separately in dashboards. - How would you generalize this logic into a multi-week cohort retention matrix covering Week 0, Week 1, Week 2, and beyond? Compute each cohort's total
cohort_sizein a standalone CTE fromusersalone so the denominator never shrinks in later weeks. Then joineventswheree.event_ts >= u.signup_date, deriveFLOOR(EXTRACT(EPOCH FROM (e.event_ts - u.signup_date)) / (7 * 86400))asweeks_since_signup, and divideCOUNT(DISTINCT e.user_id)per(signup_week, weeks_since_signup)by that cohort's fixedcohort_size. - If raw timestamps are recorded in UTC while business reporting defines Monday cohorts in New York local time, what needs to change? Convert
signup_dateinto local wall-clock time before snapping to Monday midnight—for exampleDATE_TRUNC('week', u.signup_date AT TIME ZONE 'UTC' AT TIME ZONE 'America/New_York')whensignup_dateis stored without time zone—otherwise a Sunday9 PMregistration in New York (Monday 2 AM UTC) falls into next week's cohort. Meanwhile, evaluate the 168-hour elapsed window[signup_date, signup_date + 7 days)directly in UTC so Daylight Saving Time shifts do not stretch or shrink a user's observation window by an hour.
Follow-up questions
- How do you avoid understating retention for the newest cohort when users signed up fewer than seven days before the snapshot cutoff?
- How would you generalize this logic into a multi-week cohort retention matrix covering Week 0, Week 1, Week 2, and beyond?
- If raw timestamps are recorded in UTC while business reporting defines Monday cohorts in New York local time, what needs to change?
Similar questions
- Seven-Day User Retention Across Subscription Tiers
- Distinct Users with Post-Signup Activity
- Day-Seven Calendar Retention Count
- Hierarchical Event Counts by Attribute Order
- Exact Sum of Decimal Strings
- Evaluating Predictive Signals for Customer Retention
More Mixpanel interview questions
- Seven-Day User Retention Across Subscription Tiers Medium
- Distinct Users with Post-Signup Activity Medium
- Day-Seven Calendar Retention Count Medium Pro
- Evaluating Predictive Signals for Customer Retention Medium Pro
- Hierarchical Event Counts by Attribute Order Medium Pro
- Exact Sum of Decimal Strings Medium Pro