First-Week Post Totals and Week-Later Return Share
Arrays & HashingAuto-graded · 23 test casesLast updated
Group dated activity rows by user, find each user's earliest date, total posts in the first seven days, and compute the share of users active on day 7 or later.
You are given an activity log for a posting platform. Each record is a list [user_id, posting_date, num_posts]:
user_idis an integer identifying the user.posting_dateis a string inYYYY-MM-DDformat.num_postsis a non-negative integer, the number of posts the user made on that date.
Rows may appear in any order, and a user may have several rows, including several rows on the same date.
Task
For each user, define their start date as the earliest posting_date among all of that user's rows. The start date is day 0, and a row's day offset is the number of calendar days between its date and the user's start date.
Compute:
- First-week posts for each user: the sum of
num_postsover that user's rows with day offset from 0 to 6 inclusive. - Return rate across all users: the fraction of distinct users who have at least one row with day offset 7 or greater, divided by the total number of distinct users.
A row counts as activity for a user even when its num_posts is 0. This applies both to determining the start date and to the day-7-or-later check.
Output
Return a dictionary with two keys:
"users": a list with one entry per distinct user, sorted byuser_idascending. Each entry is a dictionary with:"user_id": the user's id,"registration_date": the start date as aYYYY-MM-DDstring,"posts_first_7_days": the first-week post total.
"retention_rate": the return rate as an unrounded float. If the input is empty, return{"users": [], "retention_rate": 0.0}.
Constraints
0 <= len(user_posts) <= 10^5- All dates are valid ISO dates (
YYYY-MM-DD). num_posts >= 0- Input rows are not guaranteed to be sorted.
- Day 6 belongs to the first-week total and does not make a user retained; day 7 is excluded from the total and does make a user retained.
Examples
Example 1
Input: first_week_activity_summary([[1, '2023-01-01', 3], [1, '2023-01-02', 2], [2, '2023-02-10', 1], [2, '2023-02-15', 4], [3, '2023-03-05', 1]])
Output: {'users': [{'user_id': 1, 'registration_date': '2023-01-01', 'posts_first_7_days': 5}, {'user_id': 2, 'registration_date': '2023-02-10', 'posts_first_7_days': 5}, {'user_id': 3, 'registration_date': '2023-03-05', 'posts_first_7_days': 1}], 'retention_rate': 0}
Hints
Hint 1
Make one pass to find each user's earliest date. Do not assume the first row you see for a user is the earliest.
Hint 2
Once you have each user's start date, convert each row to a day offset using real date objects and handle each row by its offset: 0 to 6 adds to the total, 7 or more marks the user as returned.
Hint 3
Track returned users in a set so that many late rows still count a user only once, and divide by the number of distinct users (guarding against an empty input).
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Everything depends on one value per user: the start date, which is the earliest date in that user's rows. So the solution has two passes.
- First pass: parse each date into a
dateobject and record the minimum date per user in a dictionary. Keep the parsed rows so the dates are not parsed twice. Because rows are unsorted, always compare dates rather than trusting the first row seen. - Second pass: for each row, compute
delta = (date - start_date).days.- If
0 <= delta < 7, addnum_poststo that user's first-week total. - If
delta >= 7, add the user to aretainedset.
- If
- Build the output: iterate over users in sorted order and emit the start date as an ISO string along with the first-week total. The return rate is
len(retained) / number_of_users, or0.0when there are no users.
Why it is correct
- Since the start date is the minimum, no offset is negative. Each row falls into exactly one bucket: offsets 0 to 6 (counted in the total) or 7 and above (evidence of return). Nothing is double counted or missed.
- Returning is an existence question, so a set gives one boolean per user no matter how many late rows there are.
- The denominator is every distinct user, including those with no late activity.
- Rows with
num_posts = 0still define the start date and can still mark a user as returned, because the rules key off the row's existence. They add 0 to the total. - Boundaries: offset 6 is in the total and does not mark a return, and offset 7 is excluded from the total and does mark a return.
Complexity
- Time: O(n + u log u) for n rows and u distinct users (the sort of users dominates the extra term).
- Space: O(n) for the parsed rows plus O(u) for the per-user dictionaries.
Reference solution
from datetime import date
from collections import defaultdict
from typing import List, Dict
def first_week_activity_summary(user_posts: List[List]) -> Dict:
first_dates = {}
parsed = []
for user_id, posting_date, num_posts in user_posts:
d = date.fromisoformat(posting_date)
parsed.append((user_id, d, num_posts))
if user_id not in first_dates or d < first_dates[user_id]:
first_dates[user_id] = d
totals = defaultdict(int)
retained = set()
for user_id, d, num_posts in parsed:
delta = (d - first_dates[user_id]).days
if 0 <= delta < 7:
totals[user_id] += num_posts
if delta >= 7:
retained.add(user_id)
users = []
for user_id in sorted(first_dates):
users.append({
"user_id": user_id,
"registration_date": first_dates[user_id].isoformat(),
"posts_first_7_days": totals[user_id]
})
retention_rate = len(retained) / len(first_dates) if first_dates else 0.0
return {
"users": users,
"retention_rate": retention_rate
}