Rolling-Window Post Engagement: Reach, Length Percentiles, Self-Replies
SQL & DataAuto-graded · 13 test casesLast updated
Tests SQL/Python analytics skills: filtering soft-deleted records, distinct-count aggregation, linear-interpolation percentiles, time-windowed grouping, and tie-breaking sort logic.
You have three in-memory tables representing a simple publishing platform.
users — one row per registered account
| Field | Type | Notes |
|---|---|---|
user_id | int | primary key |
country | str | two-letter country code |
created_at | str | ISO date, e.g. "2025-08-01" |
posts — one row per published article
| Field | Type | Notes |
|---|---|---|
post_id | int | primary key |
author_id | int | references users.user_id |
created_at | str | ISO date |
comments — one row per comment attempt
| Field | Type | Notes |
|---|---|---|
comment_id | int | primary key |
post_id | int | references posts.post_id |
user_id | int | references users.user_id |
created_at | str | ISO date |
content | str | raw text |
is_deleted | bool | soft-delete flag |
Given these three tables and a reference date today (ISO string), produce analytics over the 7-day window ending on today, i.e. [today − 6 days, today] inclusive.
Work only with active comments: those whose is_deleted is False, whose created_at falls inside the window, and whose post_id and user_id both exist in the provided posts and users tables (inner-join semantics).
Return a dictionary with exactly three keys:
"top_posts" — most-reached posts
Rank every post that received at least one active comment by the number of distinct commenters (unique user_id values). Return the top 3 as a list of dicts, each with:
post_id— the post's identifierunique_commenters— count of distinct commenteruser_idsdistinct_commenter_countries— count of distinctcountryvalues among those commenters
Tie-breaking when two posts share the same unique_commenters count:
- Prefer the post with the later
posts.created_atdate. - If still tied, prefer the lower
post_id.
If fewer than 3 posts have active comments, return however many exist.
"daily_percentiles" — comment length distribution by post and day
For every (created_at, post_id) pair that appears in the active comments, compute the P50 and P90 of len(content) using linear interpolation:
- Sort the lengths for the group.
- The value at percentile
psits at position(n − 1) × pin the sorted list (0-indexed), wherenis the group size. - Interpolate linearly between the two surrounding integers when the position is not whole.
Return a list of dicts sorted by (day, post_id) ascending, each with:
day— thecreated_atdate stringpost_idp50_lenp90_len
Only include groups that contain at least one active comment (no zero-padding for missing days).
"self_commenters" — users who replied to their own posts
Identify every user who left at least one active comment on a post they authored (i.e. comment.user_id == post.author_id). Return a list of dicts sorted by self_comment_count descending, then user_id ascending, each with:
user_idself_comment_count— total active self-comments in the windowlast_self_comment_at— ISO date string of the most recent such comment
Constraints
1 ≤ len(users) ≤ 10 0001 ≤ len(posts) ≤ 10 0000 ≤ len(comments) ≤ 100 000- All
created_atvalues are valid ISO date strings ("YYYY-MM-DD"). todayis a valid ISO date string.user_idandpost_idvalues in comments may reference IDs that do not exist in their respective tables; treat those comments as non-existent (drop them).- A user may comment on the same post multiple times; each comment is an independent event.
- For
distinct_commenter_countries, count each distinctcountryvalue once regardless of how many users share it. - The window is fully inclusive on both ends:
today − 6 daysthroughtoday.
Examples
Example 1
Input: post_engagement_analytics([{'user_id': 1, 'country': 'US', 'created_at': '2025-08-01'}, {'user_id': 2, 'country': 'US', 'created_at': '2025-08-05'}, {'user_id': 3, 'country': 'CA', 'created_at': '2025-08-10'}, {'user_id': 4, 'country': 'US', 'created_at': '2025-08-20'}], [{'post_id': 10, 'author_id': 1, 'created_at': '2025-08-25'}, {'post_id': 11, 'author_id': 2, 'created_at': '2025-08-28'}, {'post_id': 12, 'author_id': 3, 'created_at': '2025-08-30'}], [{'comment_id': 100, 'post_id': 10, 'user_id': 2, 'created_at': '2025-08-26', 'content': 'Nice!', 'is_deleted': False}, {'comment_id': 101, 'post_id': 10, 'user_id': 3, 'created_at': '2025-08-27', 'content': 'Great post', 'is_deleted': False}, {'comment_id': 102, 'post_id': 11, 'user_id': 1, 'created_at': '2025-08-28', 'content': 'Thanks', 'is_deleted': False}, {'comment_id': 103, 'post_id': 11, 'user_id': 2, 'created_at': '2025-08-30', 'content': 'I agree', 'is_deleted': True}, {'comment_id': 104, 'post_id': 12, 'user_id': 4, 'created_at': '2025-08-31', 'content': 'Wow', 'is_deleted': False}, {'comment_id': 105, 'post_id': 12, 'user_id': 1, 'created_at': '2025-09-01', 'content': 'Following', 'is_deleted': False}, {'comment_id': 106, 'post_id': 12, 'user_id': 3, 'created_at': '2025-09-01', 'content': 'Awesome insights', 'is_deleted': False}, {'comment_id': 107, 'post_id': 10, 'user_id': 1, 'created_at': '2025-09-01', 'content': 'Self', 'is_deleted': False}], '2025-09-01')
Output: {'top_posts': [{'post_id': 12, 'unique_commenters': 3, 'distinct_commenter_countries': 2}, {'post_id': 10, 'unique_commenters': 3, 'distinct_commenter_countries': 2}, {'post_id': 11, 'unique_commenters': 1, 'distinct_commenter_countries': 1}], 'daily_percentiles': [{'day': '2025-08-26', 'post_id': 10, 'p50_len': 5, 'p90_len': 5}, {'day': '2025-08-27', 'post_id': 10, 'p50_len': 10, 'p90_len': 10}, {'day': '2025-08-28', 'post_id': 11, 'p50_len': 6, 'p90_len': 6}, {'day': '2025-08-31', 'post_id': 12, 'p50_len': 3, 'p90_len': 3}, {'day': '2025-09-01', 'post_id': 10, 'p50_len': 4, 'p90_len': 4}, {'day': '2025-09-01', 'post_id': 12, 'p50_len': 12.5, 'p90_len': 15.3}], 'self_commenters': [{'user_id': 1, 'self_comment_count': 1, 'last_self_comment_at': '2025-09-01'}, {'user_id': 3, 'self_comment_count': 1, 'last_self_comment_at': '2025-09-01'}]}
Hints
Hint 1
Build a single filtered list of active comments first (in-window, not deleted, both post and user exist), then derive all three outputs from it — this avoids re-scanning the raw data multiple times.
Hint 2
For top_posts, use a dict keyed by post_id to accumulate a set of commenter user_ids; then compute country cardinality by looking up each uid in your user map. The sort key needs three components: (-unique_commenters, -post_created_at_as_ordinal, post_id).
Hint 3
The linear-interpolation percentile formula is: position = (n-1) * p; result = sorted_values[floor(position)] + (sorted_values[ceil(position)] - sorted_values[floor(position)]) * fractional_part. For a single-element group, P50 == P90 == that element.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The key insight is that all three outputs draw from the same population: comments that are not deleted, fall within the 7-day window, and reference posts and users that actually exist. Build that filtered list once, then derive everything from it in a single pass.
Step 1 — Build lookup maps and filter
Convert users and posts into dicts keyed by their IDs. This makes existence checks and attribute lookups O(1). Then scan comments once, keeping only rows that pass all four gates: is_deleted is false, the date is within [today − 6, today], the post exists, and the user exists. This is equivalent to a filtered inner join.
Step 2 — One pass over active comments
Iterate the filtered list and populate three accumulators simultaneously:
commenters: maps eachpost_idto a set of commenteruser_ids. Using a set ensures duplicates are ignored automatically.daily_lengths: maps each(day, post_id)pair to a list oflen(content)values.self_comments: maps eachuser_idto a list of comment dates, but only whencomment.user_id == post.author_id.
Step 3 — top_posts
Iterate commenters to build a list of summary dicts. The country count requires looking up each user_id in user_by_id and collecting a set of country codes. Sort with a three-component key: descending commenter count, descending post creation date (converted to an integer ordinal for easy negation), then ascending post_id. Slice to three.
Step 4 — daily_percentiles
For each (day, post_id) group, apply linear interpolation at positions 0.5 and 0.9. The formula is:
position = (n - 1) * p
result = sorted[floor(position)] + fraction * (sorted[ceil(position)] - sorted[floor(position)])
When n == 1, both percentiles equal the single value. Sort the output by (day, post_id) before returning.
Step 5 — self_commenters
Each entry in self_comments already has the right shape. Compute count from list length and last_self_comment_at from max() on ISO strings (lexicographic order matches chronological for YYYY-MM-DD). Sort descending by count, then ascending by user_id.
Why it is correct
- Filtering once before any aggregation ensures all three metrics share the exact same definition of "active comment". There is no risk of counting a deleted comment in one output but not another.
- A
setincommentershandles users who comment multiple times on the same post: they contribute one tounique_commentersbut each comment still appears indaily_lengths. - The
PERCENTILE_CONTlinear-interpolation definition is standard: position(n−1)·pin the 0-indexed sorted list. One-element groups naturally return that single value without any special casing beyond then==1guard. - ISO date strings (
YYYY-MM-DD) sort correctly as plain strings, somax()on a list of them gives the rightlast_self_comment_at.
Complexity
Let C = total comments, P = posts, U = users, A = active comments after filtering.
- Time: O(C + P + U) to build maps and filter, O(A) for the accumulator pass, O(A log A) for percentile sorts and final orderings. Overall O(C + P + U + A log A).
- Space: O(P + U + A) for maps and accumulators.
Edge cases
- Window boundaries are inclusive on both ends. A comment dated exactly
todayor exactlytoday − 6is included. - Fewer than 3 eligible posts:
top_postsreturns however many exist; slicing beyond the list length is safe in Python. - Deleted comments are excluded everywhere, including from self-comment counts.
- Orphan comments (referencing a missing post or user ID) are dropped before all aggregations.
- Single comment in a group: P50 and P90 both equal
len(content)for that one comment. - Repeated commenter: counted once toward
unique_commentersbut each of their comments contributes separately to the length distribution.
Full solution
from datetime import date, timedelta
from typing import Dict, List
def post_engagement_analytics(
users: List[Dict],
posts: List[Dict],
comments: List[Dict],
today: str,
) -> Dict:
end = date.fromisoformat(today)
start = end - timedelta(days=6)
user_by_id = {u["user_id"]: u for u in users}
post_by_id = {p["post_id"]: p for p in posts}
active = [
c for c in comments
if not c["is_deleted"]
and start <= date.fromisoformat(c["created_at"]) <= end
and c["post_id"] in post_by_id
and c["user_id"] in user_by_id
]
commenters: Dict[int, set] = {}
daily_lengths: Dict[tuple, list] = {}
self_comments: Dict[int, list] = {}
for c in active:
pid = c["post_id"]
uid = c["user_id"]
day = c["created_at"]
commenters.setdefault(pid, set()).add(uid)
daily_lengths.setdefault((day, pid), []).append(len(c["content"]))
if post_by_id[pid]["author_id"] == uid:
self_comments.setdefault(uid, []).append(day)
# (a) top_posts
top_posts = []
for pid, uid_set in commenters.items():
countries = {user_by_id[uid]["country"] for uid in uid_set}
top_posts.append({
"post_id": pid,
"unique_commenters": len(uid_set),
"distinct_commenter_countries": len(countries),
})
top_posts.sort(
key=lambda row: (
-row["unique_commenters"],
-date.fromisoformat(post_by_id[row["post_id"]]["created_at"]).toordinal(),
row["post_id"],
)
)
top_posts = top_posts[:3]
# (b) daily_percentiles
def interpolated_percentile(values: list, p: float) -> float:
values = sorted(values)
n = len(values)
if n == 1:
return float(values[0])
position = (n - 1) * p
lower = int(position)
upper = min(lower + 1, n - 1)
fraction = position - lower
return values[lower] + (values[upper] - values[lower]) * fraction
daily = []
for (day, pid), lengths in sorted(daily_lengths.items()):
daily.append({
"day": day,
"post_id": pid,
"p50_len": interpolated_percentile(lengths, 0.5),
"p90_len": interpolated_percentile(lengths, 0.9),
})
# (c) self_commenters
self_rows = []
for uid, timestamps in self_comments.items():
self_rows.append({
"user_id": uid,
"self_comment_count": len(timestamps),
"last_self_comment_at": max(timestamps),
})
self_rows.sort(key=lambda row: (-row["self_comment_count"], row["user_id"]))
return {
"top_posts": top_posts,
"daily_percentiles": daily,
"self_commenters": self_rows,
}