Day-30 Cohort Retention from Signup and Activity Logs
SQL & DataAuto-graded · 18 test casesLast updated
Group users into signup-date cohorts and count who was active exactly 30 days later, using sets and date arithmetic with careful handling of duplicates.
Day-30 Retention by Signup Cohort
You have two logs from a personal-finance app, each given as a list of dictionaries:
signup_records: each item has"user_id"and"signup_date". Dates are ISO strings ("YYYY-MM-DD").activity_records: each item has"user_id"and"activity_date", also ISO date strings.
A cohort is the group of users who share the same signup date. A user is retained if they have at least one activity record dated exactly 30 calendar days after their signup date. Activity on day 29, day 31, or any other day does not count.
Return one summary row per cohort.
Output format
Return a list of dictionaries, one per distinct signup date, sorted by signup_date ascending. Each dictionary has these keys:
"signup_date": the cohort's date string, exactly as given in the input."cohort_size": the number of distinct users in that cohort."retained_users": the number of distinct users in that cohort who were active exactly 30 days after signup."retention_rate":retained_users / cohort_sizeas a plain fraction (for example0.5, not50). Do not round it and do not multiply by 100.
Rules
- A user counts at most once per cohort, even if
signup_recordslists the same user and date several times. - Several activity rows for the same user on the same day count as a single retained user.
- Activity rows for users who do not appear in
signup_recordsare ignored. - A cohort with no retained users still appears in the output, with
retained_usersequal to0andretention_rateequal to0.0. - If there are no signup records, return an empty list.
- Compute "30 days later" with real calendar arithmetic, so month and year boundaries and leap years are handled correctly.
Constraints
user_idvalues are strings. Compare them as given.- All dates are valid ISO
YYYY-MM-DDstrings. - The input lists may be empty.
- Every cohort in the output has at least one user.
Examples
Example 1
Input: compute_day30_retention([{'user_id': '1', 'signup_date': '2023-01-01'}, {'user_id': '2', 'signup_date': '2023-01-01'}], [{'user_id': '1', 'activity_date': '2023-01-31'}])
Output: [{'signup_date': '2023-01-01', 'cohort_size': 2, 'retained_users': 1, 'retention_rate': 0.5}]
Example 2
Input: compute_day30_retention([{'user_id': '1', 'signup_date': '2023-01-01'}, {'user_id': '2', 'signup_date': '2023-01-01'}, {'user_id': '3', 'signup_date': '2023-01-02'}], [{'user_id': '1', 'activity_date': '2023-01-31'}, {'user_id': '1', 'activity_date': '2023-01-31'}, {'user_id': '3', 'activity_date': '2023-02-01'}])
Output: [{'signup_date': '2023-01-01', 'cohort_size': 2, 'retained_users': 1, 'retention_rate': 0.5}, {'signup_date': '2023-01-02', 'cohort_size': 1, 'retained_users': 1, 'retention_rate': 1}]
Hints
Hint 1
Think of each cohort as the set of distinct user ids that signed up on that date. Using a set removes duplicate signup rows for free.
Hint 2
Put all (user_id, activity_date) pairs into a set so that checking whether a user was active on one specific date takes constant time, and repeated activity rows collapse automatically.
Hint 3
For each cohort, parse the signup date, add 30 days with a timedelta, convert back to an ISO string, and count the cohort users whose (user_id, target_date) pair is in the activity set. Remember to sort cohorts by date.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The task has a denominator and a numerator for each signup date.
- Build cohorts. Walk through the signup records and put each user id into a set keyed by signup date. Using a set means duplicate signup rows are counted once, and the set's length is the cohort size.
- Index activity. Put every
(user_id, activity_date)pair into one set. This removes repeated activity on the same day and gives constant-time lookups. Activity from users who never signed up is never queried, so it is ignored automatically. - Count retained users. For each cohort, in sorted date order, parse the signup date, add 30 days with
timedelta, and format the result back as an ISO string. Count the cohort members whose(user_id, target_date)pair is in the activity set. - Emit the row. Output the date, the cohort size, the retained count, and
retained / cohort_size. The rate is left unrounded.
Why it is correct
- The cohort set holds each user once per signup date, so duplicate signup rows cannot inflate the denominator.
- The activity set holds each user-day once, so several events on day 30 cannot inflate the numerator.
- The lookup uses an exact date match, so activity on day 29 or 31 is not counted.
- Cohorts are built from the signup data alone, so a cohort with no matching activity still appears, with 0 retained users and a rate of 0.0.
datearithmetic handles month lengths and leap years. ISO date strings sort in chronological order, so sorting the keys sorts the cohorts by date.
Complexity
Let U be the number of signup records, A the number of activity records, and C the number of cohorts.
- Time: O(U + A + C log C). Building the sets is linear, each membership check is O(1) on average, and sorting the cohort keys costs O(C log C).
- Space: O(U + A) for the cohort sets and the activity pair set.
Reference solution
from datetime import date, timedelta
from collections import defaultdict
from typing import List, Dict
def compute_day30_retention(signup_records: List[Dict[str, str]], activity_records: List[Dict[str, str]]) -> List[Dict[str, object]]:
cohorts = defaultdict(set)
for row in signup_records:
cohorts[row["signup_date"]].add(row["user_id"])
active_pairs = set()
for row in activity_records:
active_pairs.add((row["user_id"], row["activity_date"]))
result = []
for signup_date in sorted(cohorts):
target = (date.fromisoformat(signup_date) + timedelta(days=30)).isoformat()
members = cohorts[signup_date]
retained = sum(1 for uid in members if (uid, target) in active_pairs)
size = len(members)
result.append({
"signup_date": signup_date,
"cohort_size": size,
"retained_users": retained,
"retention_rate": retained / size if size else 0.0,
})
return result