Monthly Signup Cohorts: Day-30 Return Rate
Arrays & HashingAuto-graded · 21 test casesLast updated
Group users by first-activity month and compute the share who return exactly 30 days later, excluding users whose day 30 lies beyond the last observed date.
Day-30 Return Rate by Signup Month
You are given a log of user activity. Each entry is a dictionary with two keys:
user_id: the user's identifier.activity_date: the calendar day of the activity, given as a string such as"2023-01-31". A full ISO timestamp containing aT(for example"2023-01-31T14:05:00") may also appear; only the calendar date part matters.
A user's signup day is the earliest activity_date found for that user anywhere in the log.
A user is retained if they have at least one activity on exactly the day signup day + 30 days. Activity on any other day (day 29, day 31, and so on) does not count, and several records on day 30 count only once.
Task
Group users into cohorts by the calendar month of their signup day, formatted "YYYY-MM". For each cohort, compute
retention_rate = (number of retained users in the cohort) / (number of users in the cohort).
Excluding users who cannot be observed
Let last_day be the latest activity date in the whole log. A user is eligible only if their day 30 has been observed, meaning signup day + 30 days <= last_day. The boundary is inclusive. Users who are not eligible are ignored completely: they are neither counted in a cohort's total nor counted as retained.
Output
Return a list of dictionaries with keys "cohort_month" and "retention_rate", one per cohort that has at least one eligible user, sorted by cohort_month in ascending order.
- A cohort in which nobody is retained still appears, with a rate of
0. - The rate is the ratio of two counts (a number between 0 and 1).
- If the input is empty, or no user is eligible, return an empty list.
- "30 days later" means a plain offset of 30 calendar days, not "one month later". A user's cohort depends only on the signup month, even if day 30 falls in the next month.
Constraints
0 <= len(rows) <= 10^5- Every row contains a valid
user_idand a validactivity_date. - Rows may be in any order and may contain duplicates.
- Dates are valid calendar dates in ISO format.
Examples
Example 1
Input: cohort_day30_retention([{'user_id': 1, 'activity_date': '2023-01-01'}, {'user_id': 1, 'activity_date': '2023-01-31'}, {'user_id': 2, 'activity_date': '2023-01-10'}, {'user_id': 2, 'activity_date': '2023-01-20'}, {'user_id': 3, 'activity_date': '2023-02-01'}, {'user_id': 3, 'activity_date': '2023-03-03'}, {'user_id': 4, 'activity_date': '2023-02-15'}, {'user_id': 4, 'activity_date': '2023-04-01'}])
Output: [{'cohort_month': '2023-01', 'retention_rate': 0.5}, {'cohort_month': '2023-02', 'retention_rate': 0.5}]
Example 2
Input: cohort_day30_retention([{'user_id': 10, 'activity_date': '2024-01-01'}, {'user_id': 10, 'activity_date': '2024-01-31'}, {'user_id': 11, 'activity_date': '2024-02-01'}, {'user_id': 11, 'activity_date': '2024-03-02'}, {'user_id': 12, 'activity_date': '2024-04-01'}])
Output: [{'cohort_month': '2024-01', 'retention_rate': 1}, {'cohort_month': '2024-02', 'retention_rate': 1}]
Example 3
Input: cohort_day30_retention([{'user_id': 1, 'activity_date': '2023-01-01'}, {'user_id': 1, 'activity_date': '2023-01-31'}, {'user_id': 1, 'activity_date': '2023-01-31'}, {'user_id': 2, 'activity_date': '2023-01-15'}, {'user_id': 2, 'activity_date': '2023-02-14'}, {'user_id': 3, 'activity_date': '2023-03-01'}, {'user_id': 4, 'activity_date': '2023-04-01'}])
Output: [{'cohort_month': '2023-01', 'retention_rate': 1}, {'cohort_month': '2023-03', 'retention_rate': 0}]
Hints
Hint 1
Make one pass to find each user's earliest date and another to find the latest date in the whole log.
Hint 2
A user is eligible only when their signup day plus 30 days does not exceed the latest date overall. Everything that follows only concerns eligible users.
Hint 3
Keep a per-user flag instead of counting rows, so duplicate day-30 records cannot inflate the numerator. Count totals per cohort over all eligible users, so cohorts with zero retained still show up with rate 0.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
- Convert every
activity_dateto a calendar date and record the latest date in the log,last_day. - Compute each user's signup day as the minimum date seen for that user.
- Keep only eligible users, those whose signup day is at most
last_day - 30 days. This ensures their day 30 falls inside the observed window (the boundary is inclusive). - Scan the events again. If an event belongs to an eligible user and its date equals
signup + 30 days, add that user to aretainedset. Using a set means duplicate day-30 rows count once. - For each eligible user, add 1 to the total of their signup-month cohort, and add 1 to that cohort's retained count if the user is in
retained. - Output
retained / totalfor each cohort, sorted by month.
Why it is correct
- Every user has exactly one signup day, so belongs to exactly one cohort.
- The equality test on
signup + 30 daysmatches the exact-day rule, so activity on days 29 or 31 is ignored. - Totals are built from all eligible users, not only those with a day-30 match, so non-retained users stay in the denominator and cohorts with no retained users appear with rate 0.
- The cutoff filter removes users who cannot yet be observed, so recent cohorts are not unfairly penalized.
- Cohorts are keyed by signup month, so a day 30 that lands in the next month does not change the cohort.
Complexity
With n rows and u users: time is O(n + u + c log c) for c cohorts (the sort is negligible), and space is O(n + u).
Reference solution
from datetime import date, datetime, timedelta
from typing import List, Dict
def _to_date(value):
if isinstance(value, datetime):
return value.date()
if isinstance(value, date):
return value
text = str(value)
if "T" in text:
return datetime.fromisoformat(text).date()
return date.fromisoformat(text)
def cohort_day30_retention(rows: List[Dict[str, object]]) -> List[Dict[str, object]]:
if not rows:
return []
events = []
last_day = None
for row in rows:
uid = row["user_id"]
day = _to_date(row["activity_date"])
events.append((uid, day))
if last_day is None or day > last_day:
last_day = day
first_seen = {}
for uid, day in events:
if uid not in first_seen or day < first_seen[uid]:
first_seen[uid] = day
limit = last_day - timedelta(days=30)
eligible = {uid: d for uid, d in first_seen.items() if d <= limit}
retained = set()
for uid, day in events:
start = eligible.get(uid)
if start is not None and day == start + timedelta(days=30):
retained.add(uid)
totals = {}
kept = {}
for uid, start in eligible.items():
month = start.strftime("%Y-%m")
totals[month] = totals.get(month, 0) + 1
if uid in retained:
kept[month] = kept.get(month, 0) + 1
return [
{"cohort_month": m, "retention_rate": kept.get(m, 0) / total}
for m, total in sorted(totals.items())
]