Cohort Return Rates by Months Since First Visit
Arrays & HashingAuto-graded · 19 test casesLast updated
Group users by the month of their first activity, then compute the fraction of each cohort that was active in every later month offset, using calendar-month arithmetic.
Cohort Return Rates by Months Since First Visit
You are given a log of user visits. Each entry is a pair [user_id, visit_date], where visit_date is a string in YYYY-MM-DD format. A user may appear many times, including several times on the same day or in the same month.
Build a cohort retention table as follows.
-
A user's cohort is the calendar month (formatted
YYYY-MM) of their earliest visit. -
For any month in which a user visited, its month offset is the number of calendar months between that month and the user's cohort. The cohort month itself has offset
0, the following month has offset1, and so on. Count calendar months, not days: January 31 and February 1 are one month apart, and December 2023 to January 2024 is one month apart. -
For a given
(cohort, offset)pair, the retention rate is:(number of distinct users in that cohort who visited at least once during the month at that offset) / (total number of distinct users in that cohort)
Each user counts at most once per month, no matter how many visits they made in it.
Return a list of dictionaries, one per (cohort, offset) pair in which at least one cohort member visited. Pairs with no returning users are omitted, so there are no rows with a rate of zero. Each dictionary has exactly these keys:
"cohort_month": the cohort as aYYYY-MMstring"month_number": the integer offset"retention_rate": the rate as a plain fraction between 0 and 1, computed by ordinary division. Do not round it and do not multiply it by 100.
Sort the result by cohort_month ascending (as a string, which matches chronological order), and then by month_number ascending. If the log is empty, return an empty list.
Constraints
- Every date is a valid string of the form
YYYY-MM-DD. - Dates span at most about two years.
- Every
user_idis hashable (for example an integer), and users are distinguished by theiruser_idvalue. - The log may be empty.
- Because of the omission rule, every cohort always has a row with
month_number = 0and a rate of exactly1.
Examples
Example 1
Input: cohort_retention_table([[1, '2023-01-05'], [1, '2023-02-10'], [2, '2023-01-20'], [3, '2023-02-01']])
Output: [{'cohort_month': '2023-01', 'month_number': 0, 'retention_rate': 1}, {'cohort_month': '2023-01', 'month_number': 1, 'retention_rate': 0.5}, {'cohort_month': '2023-02', 'month_number': 0, 'retention_rate': 1}]
Hints
Hint 1
For each user, you only care about the set of distinct `YYYY-MM` months in which they were active. Slicing the first 7 characters of the date gives you that.
Hint 2
The earliest month of a user's set is their cohort. Convert `YYYY-MM` strings to integers to get the offset as (year difference) * 12 + (month difference), instead of dividing days by 30.
Hint 3
Keep a count of users per cohort and, for every (cohort, offset) pair, a set of user ids that were active. The rate is the size of that set divided by the cohort size. Finally sort the pairs.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
- Collapse visits to months. For each user, collect the set of distinct
YYYY-MMstrings from their visits. Using a set means that many visits in one month count once, so a rate can never exceed 1. - Find each user's cohort. The cohort is the minimum of that user's month set.
YYYY-MMstrings sort chronologically, so plain stringminworks. Increment a counter for that cohort to get the cohort size. - Compute offsets. For every active month of the user, parse the year and month as integers and compute
(year - cohort_year) * 12 + (month - cohort_month). This counts calendar months exactly and handles year rollovers (December to January gives 1). Add the user to a set stored under the key(cohort, offset). - Produce the rows. For each
(cohort, offset)key in sorted order, the rate is the size of its user set divided by the cohort's size. Only keys that actually occurred are present, which gives the required omission of zero-retention rows.
Why it is correct
- Every user is active in their own cohort month, so each is added to
(cohort, 0). That key's set size equals the cohort size, so the rate there is exactly 1. - Offsets are never negative, because a user's cohort is the earliest of their months.
- Using sets per
(cohort, offset)guarantees each user is counted once per cell, and using the distinct month set per user guarantees repeated visits in a month are ignored. - Sorting tuples
(cohort_string, offset_int)gives the required ordering: cohort chronologically, then offset ascending.
Complexity
Let N be the number of visits, and let M be the number of distinct months a user can be active in (at most about 24 here).
- Time: O(N) to build the month sets, plus O(U * M) to assign offsets for U users, plus sorting the output cells. There are at most a few hundred cells here, so the sort is O(K log K) for K output rows.
- Space: O(U * M) for the per-user month sets and the per-cell user sets.
Reference solution
from collections import defaultdict
from typing import Dict, List
def cohort_retention_table(visits: List[List[str]]) -> List[Dict[str, object]]:
# Distinct active months (YYYY-MM) for each user.
months_by_user = defaultdict(set)
for user_id, visit_date in visits:
months_by_user[user_id].add(visit_date[:7])
cohort_size = defaultdict(int)
active_users = defaultdict(set)
for user_id, months in months_by_user.items():
cohort = min(months)
cohort_size[cohort] += 1
c_year, c_month = map(int, cohort.split("-"))
for m in months:
year, month = map(int, m.split("-"))
offset = (year - c_year) * 12 + (month - c_month)
active_users[(cohort, offset)].add(user_id)
result = []
for (cohort, offset), users in sorted(active_users.items()):
result.append({
"cohort_month": cohort,
"month_number": offset,
"retention_rate": len(users) / cohort_size[cohort],
})
return result