Social Feed Reply Engagement Metrics
Easy · Data Manipulation (SQL/Python) · Data Scientist · Technical Screen
Problem Statement
Given feed activity logs and account profile records from a short-form discussion platform, compute two creator reply-engagement metrics in compute_reply_engagement_metrics(all_post, users).
Input Format
all_post: A list of dictionaries storing both root posts and replies, where each dictionary contains:post_id(int): Unique identifier of this record.post_author_id(int): Account ID of the creator of this post or reply.post_creation_time(strordatetime): Creation timestamp in UTC (for example'2025-06-10T08:00:00Z'; timestamps without an explicit offset are UTC).post_type(str): Either'post'for a root post or'reply'for a reply.post_content(str): Text body of the entry.post_parent_id(Optional[int]):Nonewhenpost_type == 'post', or the targetpost_idwhenpost_type == 'reply'. Only direct replies whosepost_parent_idreferences a root'post'record count toward root-post engagement (nested replies pointing to another'reply'or to a missing ID are ignored).
users: A list of profile dictionaries, each containing:user_id(int): Unique account identifier.age(int): Account holder's age.country(str): Country code such as'US','DE','GB', or'JP'.
Metrics to Return
Return a dictionary {"num_users": ..., "pct_users": ...} with:
num_users(7-Day Multi-Reply Creators): For each root post (post_type == 'post'), count its direct replies created at or after the root post'spost_creation_timeand at most 7 days (7 * 24hours, inclusive to the second) later. Multiple replies from the same account count as separate reply records. Return how many distinct root-post authors (post_author_id) published at least one root post that accumulated 2 or more direct replies within its 7-day window.pct_users(Share of Replied-To Creators Reached by 2+ US Repliers): Define a replied-to creator as any root-post author who received at least one direct reply on any of their root posts (across all time, with no 7-day cutoff and regardless of replier country). Using all distinct replied-to creators as the denominator (omitting creators with zero direct replies, and returning0.0when the denominator is0), compute the percentage (0.0to100.0) who received direct replies across all of their root posts combined from at least 2 distinct repliers whosecountryinusersequals'US'. Only the replier's country is checked, not the root-post author's country.
Examples
Example 1
Input:
all_post = [
{"post_id": 10, "post_author_id": 101, "post_creation_time": "2025-06-10T08:00:00Z", "post_type": "post", "post_content": "launch note", "post_parent_id": None},
{"post_id": 11, "post_author_id": 201, "post_creation_time": "2025-06-11T08:00:00Z", "post_type": "reply", "post_content": "congrats", "post_parent_id": 10},
{"post_id": 12, "post_author_id": 202, "post_creation_time": "2025-06-17T08:00:00Z", "post_type": "reply", "post_content": "nice work", "post_parent_id": 10},
{"post_id": 13, "post_author_id": 102, "post_creation_time": "2025-06-12T12:00:00Z", "post_type": "post", "post_content": "question", "post_parent_id": None},
{"post_id": 14, "post_author_id": 203, "post_creation_time": "2025-06-13T12:00:00Z", "post_type": "reply", "post_content": "answer", "post_parent_id": 13},
{"post_id": 15, "post_author_id": 103, "post_creation_time": "2025-06-14T00:00:00Z", "post_type": "post", "post_content": "quiet post", "post_parent_id": None},
]
users = [
{"user_id": 101, "age": 29, "country": "DE"},
{"user_id": 102, "age": 34, "country": "US"},
{"user_id": 103, "age": 22, "country": "US"},
{"user_id": 201, "age": 26, "country": "US"},
{"user_id": 202, "age": 31, "country": "US"},
{"user_id": 203, "age": 27, "country": "JP"},
]
Output:
{"num_users": 1, "pct_users": 50.0}
Walk-through:
- Root post 10 (creator 101) receives reply 11 (+1 day) and reply 12 (+7 days exact, inclusive), giving 2 replies inside 7 days. Root post 13 (creator 102) receives 1 reply, and root post 15 (creator 103) receives 0. Thus num_users = 1.
- Creators 101 and 102 each received at least one direct reply (denominator = 2; creator 103 is excluded). Creator 101 heard from 2 distinct 'US' repliers (201 and 202), whereas creator 102 only heard from 'JP' user 203, yielding 100.0 * 1 / 2 = 50.0.
Example 2
Input:
all_post = [
{"post_id": 50, "post_author_id": 301, "post_creation_time": "2025-09-01T10:00:00Z", "post_type": "post", "post_content": "part 1", "post_parent_id": None},
{"post_id": 51, "post_author_id": 301, "post_creation_time": "2025-09-05T10:00:00Z", "post_type": "post", "post_content": "part 2", "post_parent_id": None},
{"post_id": 52, "post_author_id": 401, "post_creation_time": "2025-09-02T10:00:00Z", "post_type": "reply", "post_content": "first", "post_parent_id": 50},
{"post_id": 53, "post_author_id": 402, "post_creation_time": "2025-09-10T10:00:00Z", "post_type": "reply", "post_content": "late on p1", "post_parent_id": 50},
{"post_id": 54, "post_author_id": 401, "post_creation_time": "2025-09-06T10:00:00Z", "post_type": "reply", "post_content": "on p2", "post_parent_id": 51},
{"post_id": 55, "post_author_id": 403, "post_creation_time": "2025-09-02T11:00:00Z", "post_type": "reply", "post_content": "nested", "post_parent_id": 52},
]
users = [
{"user_id": 301, "age": 35, "country": "GB"},
{"user_id": 401, "age": 24, "country": "US"},
{"user_id": 402, "age": 29, "country": "US"},
{"user_id": 403, "age": 33, "country": "US"},
]
Output:
{"num_users": 0, "pct_users": 100.0}
Walk-through:
- Reply 55 targets reply 52 rather than a root post, so it is ignored.
- On root post 50, reply 52 (+1 day) is inside 7 days while reply 53 (+9 days) is outside; on root post 51, reply 54 (+1 day) gives just 1 reply. Neither individual post reaches 2 replies within 7 days, so num_users = 0.
- For pct_users, creator 301 is the sole replied-to creator, and pooling across posts 50 and 51 (with no 7-day limit) collects distinct 'US' repliers {401, 402} of size 2, giving 100.0.
Constraints
0 <= len(all_post), len(users) <= 10^5.- Input rows in
all_postare not guaranteed to be sorted chronologically; a reply may appear before its parent post in the list. - Some
post_author_idvalues inall_postmay have no corresponding record inusers(treat their country as non-'US'). - The 7-day window in
num_usersis exact and inclusive on both boundaries:0 seconds <= reply_time - post_time <= 7 * 86,400 seconds.
Step-by-step walkthrough
Separate the rules for both metrics
We receive two tables as lists of dictionaries —
all_post(storing both root posts and replies) andusers— and must return{"num_users": ..., "pct_users": ...}.The two metrics look similar at first glance, yet they differ on almost every aggregation rule. Lining up those differences first avoids subtle analytics bugs:
Rule Metric 1 (num_users) Metric 2 (pct_users) --------------------- ---------------------------------- ----------------------------------------- Which posts count? Root posts (post_type='post') Root posts (post_type='post') Which replies count? Direct replies to a root post Direct replies to a root post Time window? 0 <= reply_time - post_time <= 7d No time limit (all-time replies count) Grouping level? Count per POST first, then authors Pool across ALL posts of each author What reaches >= 2? 2+ reply ROWS (same replier ok) 2+ DISTINCT US repliers (country == 'US') Output Count of distinct qualifying users 100 * qualified / users with >= 1 replyTwo rules are especially important: - Nested replies do not count: both metrics examine direct replies to root posts (
post_type == 'post'). If Reply55haspost_parent_idpointing to Reply52, Reply55is ignored by both metrics. - Empty denominator: when zero root posts receive any direct reply,pct_usersreturns0.0rather than dividing by zero.Why nested loops are slow and how indexing fixes it
A brute-force scan loops over every root post and searches the entire
all_postlist to find replies whosepost_parent_idmatches that post'spost_id. WithProws inall_post, that nested scan takesO(P^2)comparisons — billions of steps oncePreaches100,000.All that inner loop does is join each reply to its parent post. Storing root posts in a dictionary keyed by
post_iddrops each parent lookup fromO(P)toO(1)average time! Running two linear passes overall_postalso handles out-of-order logs where a reply appears before its parent post.Parse UTC timestamps and match direct replies
Timestamps arrive as ISO-8601 strings such as
'2025-06-10T08:00:00Z'. Comparing raw strings breaks if formatting varies, so we parse them into timezone-awaredatetimeobjects in UTC (replacing a trailing'Z'with'+00:00'sodatetime.fromisoformatworks cleanly across Python versions).Then
index_posts_and_repliesmakes two straightforward passes: 1. Pass 1 records every root post (post_type == 'post') inoriginals[post_id] = (author_id, created_at). 2. Pass 2 collects every'reply'whosepost_parent_idis inoriginals. That singleparent_id in originalscheck filters out both replies-to-replies and replies referencing missing IDs.REPLY_WINDOW = timedelta(days=7) def parse_utc_time(raw_time: Any) -> datetime: # Convert an ISO-8601 string (or existing datetime) into a timezone-aware UTC datetime. if isinstance(raw_time, datetime): moment = raw_time else: text = raw_time.strip() # Replace trailing 'Z' with '+00:00' so fromisoformat works across Python versions. if text.endswith(("Z", "z")): text = text[:-1] + "+00:00" moment = datetime.fromisoformat(text) # The problem states timestamps are UTC when no explicit timezone offset is attached. if moment.tzinfo is None: moment = moment.replace(tzinfo=timezone.utc) return moment def index_posts_and_replies( all_post: List[Dict], ) -> Tuple[Dict[Any, Tuple[Any, datetime]], List[Tuple[Any, Any, datetime]]]: # originals: {post_id: (post_author_id, post_creation_time)} for original posts only. originals: Dict[Any, Tuple[Any, datetime]] = {} for row in all_post: if row["post_type"] == "post": post_id = row["post_id"] author_id = row["post_author_id"] created_at = parse_utc_time(row["post_creation_time"]) originals[post_id] = (author_id, created_at) # direct_replies: [(parent_post_id, replier_id, reply_time), ...] # Two separate passes ensure a reply listed before its parent post is still matched, # and checking `parent_id in originals` ignores replies-to-replies and missing parents. direct_replies: List[Tuple[Any, Any, datetime]] = [] for row in all_post: parent_id = row["post_parent_id"] if row["post_type"] == "reply" and parent_id in originals: replier_id = row["post_author_id"] reply_time = parse_utc_time(row["post_creation_time"]) direct_replies.append((parent_id, replier_id, reply_time)) return originals, direct_repliesCompute Metric 1: count quick replies per post, then deduplicate authors
Why must we count per
post_idbefore grouping byauthor_id? Because a creator who publishes two posts that each receive 1 quick reply has 2 total replies, yet 0 posts with >= 2 replies!So we: 1. Check
timedelta(0) <= reply_time - post_time <= timedelta(days=7)for each direct reply and incrementquick_reply_counts[parent_id]. Both endpoints are inclusive (<=), so a reply arriving at the exact same second or7 * 24hours later counts. 2. Add the author of every post withreply_count >= 2into aset(qualifying_authors), so a creator with several popular posts is still counted once.def count_authors_with_busy_post( originals: Dict[Any, Tuple[Any, datetime]], direct_replies: List[Tuple[Any, Any, datetime]], ) -> int: # Task A Step 1: count quick replies per original post (not per author!). # quick_reply_counts: {original_post_id: number_of_replies_within_7_days} quick_reply_counts: Dict[Any, int] = {} for parent_id, _replier_id, reply_time in direct_replies: _post_author_id, post_time = originals[parent_id] elapsed = reply_time - post_time # Both 0 seconds and exactly 7 days are included; negative gaps (before post) are not. if timedelta(0) <= elapsed <= REPLY_WINDOW: quick_reply_counts[parent_id] = quick_reply_counts.get(parent_id, 0) + 1 # Task A Step 2: collect distinct authors who own at least one post with >= 2 quick replies. qualifying_authors: Set[Any] = set() for post_id, reply_count in quick_reply_counts.items(): if reply_count >= 2: post_author_id, _post_time = originals[post_id] qualifying_authors.add(post_author_id) return len(qualifying_authors)Compute Metric 2: track all reply receivers and their distinct US repliers
Metric 2 contains a classic denominator trap: who belongs in the denominator? Every creator whose root posts received at least one direct reply — even when every reply came from outside
'US'! Filtering out non-US replies up front would drop creators whose audience is outside the US, shrinking the denominator and inflatingpct_users.We track both the denominator and numerator in one dictionary,
us_repliers_by_author: - Whenever any direct reply arrives forpost_author_id, we ensureus_repliers_by_author[post_author_id]exists (initialized to an emptyset()). Thuslen(us_repliers_by_author)equals the exact number of distinct replied-to creators. - Ifreplier_idis inus_user_ids(country == 'US'), we addreplier_idtous_repliers_by_author[post_author_id]. Because it is aset, the same US user replying across multiple posts still counts as 1 distinct replier.def pct_receivers_with_two_us_repliers( originals: Dict[Any, Tuple[Any, datetime]], direct_replies: List[Tuple[Any, Any, datetime]], users: List[Dict], ) -> float: # us_user_ids: set of user_ids whose country is 'US' for O(1) membership checks. us_user_ids: Set[Any] = set() for user in users: if user.get("country") == "US": us_user_ids.add(user["user_id"]) # us_repliers_by_author: {original_post_author_id: {distinct_us_replier_ids}} # IMPORTANT: create an entry for EVERY reply (even non-US replies) so the dictionary keys # represent the exact denominator: all distinct authors who received >= 1 reply. us_repliers_by_author: Dict[Any, Set[Any]] = {} for parent_id, replier_id, _reply_time in direct_replies: post_author_id, _post_time = originals[parent_id] if post_author_id not in us_repliers_by_author: us_repliers_by_author[post_author_id] = set() if replier_id in us_user_ids: us_repliers_by_author[post_author_id].add(replier_id) # Guard against division by zero when no original post received any reply. total_receivers = len(us_repliers_by_author) if total_receivers == 0: return 0.0 qualified_receivers = 0 for distinct_us_repliers in us_repliers_by_author.values(): if len(distinct_us_repliers) >= 2: qualified_receivers += 1 return 100.0 * qualified_receivers / total_receiversTrace Example 1 and Example 2
Example 1: Root posts are
10(creator101,'DE'),13(creator102,'US'), and15(creator103,'US').Reply Parent Replier (Country) Reply Time Elapsed In 7d Window? ----- ------ ----------------- -------------------- -------- ------------- 11 10 201 (US) 2025-06-11T08:00:00Z 1 day Yes 12 10 202 (US) 2025-06-17T08:00:00Z 7 days Yes (inclusive!) 14 13 203 (JP) 2025-06-13T12:00:00Z 1 day Yes Metric 1: quick_reply_counts = {10: 2, 13: 1} -> qualifying_authors = {101} -> num_users = 1 Metric 2: us_repliers_by_author = {101: {201, 202}, 102: set()} (103 had 0 replies -> excluded) 1 of 2 receivers qualifies -> pct_users = 50.0Notice that Creator
101living in'DE'still qualifies in Metric 2 because only the repliers' countries (201and202in'US') matter!Example 2: Creator
301publishes root posts50and51: - Reply55points to Reply52(not inoriginals), so it is skipped immediately. - Post50gets reply52(+1 day, in window) and reply53(+9 days, outside 7-day window) ->quick_reply_counts[50] = 1. - Post51gets reply54(+1 day, in window) ->quick_reply_counts[51] = 1. - Metric 1: neither post reaches>= 2, sonum_users = 0. - Metric 2: pooling across both posts with no time limit givesus_repliers_by_author[301] = {401, 402}(replier401deduplicated, late replier402included), so1of1receiver qualifies andpct_users = 100.0.Complete solution
from typing import Any, Dict, List, Optional, Set, Tuple from datetime import datetime, timedelta, timezone # Task A counts replies created at most 7 days (7 * 24 hours, inclusive) after the post. REPLY_WINDOW = timedelta(days=7) def parse_utc_time(raw_time: Any) -> datetime: # Convert an ISO-8601 string (or existing datetime) into a timezone-aware UTC datetime. if isinstance(raw_time, datetime): moment = raw_time else: text = raw_time.strip() # Replace trailing 'Z' with '+00:00' so fromisoformat works across Python versions. if text.endswith(("Z", "z")): text = text[:-1] + "+00:00" moment = datetime.fromisoformat(text) # The problem states timestamps are UTC when no explicit timezone offset is attached. if moment.tzinfo is None: moment = moment.replace(tzinfo=timezone.utc) return moment def index_posts_and_replies( all_post: List[Dict], ) -> Tuple[Dict[Any, Tuple[Any, datetime]], List[Tuple[Any, Any, datetime]]]: # originals: {post_id: (post_author_id, post_creation_time)} for original posts only. originals: Dict[Any, Tuple[Any, datetime]] = {} for row in all_post: if row["post_type"] == "post": post_id = row["post_id"] author_id = row["post_author_id"] created_at = parse_utc_time(row["post_creation_time"]) originals[post_id] = (author_id, created_at) # direct_replies: [(parent_post_id, replier_id, reply_time), ...] # Two separate passes ensure a reply listed before its parent post is still matched, # and checking `parent_id in originals` ignores replies-to-replies and missing parents. direct_replies: List[Tuple[Any, Any, datetime]] = [] for row in all_post: parent_id = row["post_parent_id"] if row["post_type"] == "reply" and parent_id in originals: replier_id = row["post_author_id"] reply_time = parse_utc_time(row["post_creation_time"]) direct_replies.append((parent_id, replier_id, reply_time)) return originals, direct_replies def count_authors_with_busy_post( originals: Dict[Any, Tuple[Any, datetime]], direct_replies: List[Tuple[Any, Any, datetime]], ) -> int: # Task A Step 1: count quick replies per original post (not per author!). # quick_reply_counts: {original_post_id: number_of_replies_within_7_days} quick_reply_counts: Dict[Any, int] = {} for parent_id, _replier_id, reply_time in direct_replies: _post_author_id, post_time = originals[parent_id] elapsed = reply_time - post_time # Both 0 seconds and exactly 7 days are included; negative gaps (before post) are not. if timedelta(0) <= elapsed <= REPLY_WINDOW: quick_reply_counts[parent_id] = quick_reply_counts.get(parent_id, 0) + 1 # Task A Step 2: collect distinct authors who own at least one post with >= 2 quick replies. qualifying_authors: Set[Any] = set() for post_id, reply_count in quick_reply_counts.items(): if reply_count >= 2: post_author_id, _post_time = originals[post_id] qualifying_authors.add(post_author_id) return len(qualifying_authors) def pct_receivers_with_two_us_repliers( originals: Dict[Any, Tuple[Any, datetime]], direct_replies: List[Tuple[Any, Any, datetime]], users: List[Dict], ) -> float: # us_user_ids: set of user_ids whose country is 'US' for O(1) membership checks. us_user_ids: Set[Any] = set() for user in users: if user.get("country") == "US": us_user_ids.add(user["user_id"]) # us_repliers_by_author: {original_post_author_id: {distinct_us_replier_ids}} # IMPORTANT: create an entry for EVERY reply (even non-US replies) so the dictionary keys # represent the exact denominator: all distinct authors who received >= 1 reply. us_repliers_by_author: Dict[Any, Set[Any]] = {} for parent_id, replier_id, _reply_time in direct_replies: post_author_id, _post_time = originals[parent_id] if post_author_id not in us_repliers_by_author: us_repliers_by_author[post_author_id] = set() if replier_id in us_user_ids: us_repliers_by_author[post_author_id].add(replier_id) # Guard against division by zero when no original post received any reply. total_receivers = len(us_repliers_by_author) if total_receivers == 0: return 0.0 qualified_receivers = 0 for distinct_us_repliers in us_repliers_by_author.values(): if len(distinct_us_repliers) >= 2: qualified_receivers += 1 return 100.0 * qualified_receivers / total_receivers def compute_reply_engagement_metrics(all_post: List[Dict], users: List[Dict]) -> Dict[str, float]: originals, direct_replies = index_posts_and_replies(all_post) return { "num_users": count_authors_with_busy_post(originals, direct_replies), "pct_users": pct_receivers_with_two_us_repliers(originals, direct_replies, users), }✅ Submit now — all tests should pass.
Intuition & how it works
Imagine sorting reader mail for newspaper columnists. Metric 1 (num_users) asks: "How many columnists wrote at least one article that got 2 or more letters within its first 7 days?" — so you tally letters per article first, flag the busy articles, and count unique columnists. Metric 2 (pct_users) asks: "Out of all columnists who ever got any letter, what percentage heard from at least 2 different US readers across all their articles?" — so you open a folder for every columnist who got mail, collect unique US sender IDs inside their folder, and measure what percentage of folders hold at least 2 IDs.
A naive implementation scans the entire all_post list inside a nested loop for every root post (O(P^2) time for P rows), or filters down to 'US' replies too early and accidentally drops creators who only received non-US replies from Metric 2's denominator. Instead, we build a hash index (a dictionary mapping each root post_id to its creator and timestamp for O(1) lookup) in one pass, match direct replies in a second pass, and aggregate each metric at its exact required grain.
Walk through a compact 5-row example:
- Creator 101 publishes Post 10 on June 10; 'US' User 201 replies twice to Post 10 on June 11 and June 12; Creator 102 publishes Post 13 on June 10 and 'JP' User 203 replies once on June 11.
- Indexing: originals = {10: (101, Jun 10), 13: (102, Jun 10)}, and all 3 replies match a root post.
- Metric 1: Post 10 has 2 replies within 7 days (same replier is fine because Metric 1 counts reply records), and Post 13 has 1, so num_users = 1 (Creator 101).
- Metric 2: both Creator 101 and Creator 102 received at least one reply (denominator = 2), us_repliers_by_author = {101: {201}, 102: set()} (User 201 is only 1 distinct 'US' replier!), so 0 of 2 receivers qualify and pct_users = 0.0.
Complexity
Let P be the number of rows in all_post and U be the number of rows in users.
- Time —
O(P + U)on average: we scanall_posttwice to parse timestamps and pair direct replies (O(P)), scanusersonce to buildus_user_ids(O(U)), and iterate over matched replies withO(1)average-time dictionary and set operations. - Space —
O(P + U):originalsanddirect_replieshold at mostPentries combined,us_user_idsholds at mostUuser IDs, and the per-creator replier sets hold at most one entry per reply (<= P).
Edge cases
- Empty tables or zero replies overall:
num_usersis0andtotal_receivers == 0returnspct_users = 0.0without raisingZeroDivisionError. - Exact 7-day boundary: a reply at the exact same second (
elapsed == 0) or7 * 24hours later (elapsed == timedelta(days=7)) counts for Metric 1; 1 second past 7 days does not. - Late replies (> 7 days): excluded from Metric 1, yet included in Metric 2 because Metric 2 has no time cutoff.
- Same user replying multiple times: counts as separate reply rows for Metric 1, but deduplicates to 1 entry inside Metric 2's
set. - Nested replies (
post_parent_idpoints to a'reply'row): ignored by both metrics becauseparent_idis absent fromoriginals, and the reply's author does not become a replied-to creator. - Creators with only non-US replies (or repliers absent from
users): still entered inus_repliers_by_authorwith an empty set so they stay in Metric 2's denominator while contributing0to the numerator. - Out-of-order input rows: a reply appearing before its parent post in
all_postis still matched becauseoriginalsis populated completely in Pass 1 before Pass 2 scans replies.
Common mistakes
- Counting Metric 1 per creator instead of per post: summing 1 quick reply on Post
50and 1 quick reply on Post51gives 2 replies for Creator301even though neither post received>= 2quick replies. - Counting Metric 2 per post instead of per creator: a creator who gets 1
'US'replier on Post50and a different'US'replier on Post51has 2 distinct'US'repliers overall and must qualify for Metric 2. - Filtering to
country == 'US'before forming the denominator: discarding non-US replies early removes creators whose replies all came from outside'US', shrinking the denominator and inflatingpct_users. - Applying the 7-day cutoff to Metric 2: Metric 2 has no time window; filtering by
REPLY_WINDOWundercounts both receivers and'US'repliers. - Returning a
[0, 1]ratio instead of a[0, 100]percentage, or using integer division in SQL (100 * int / inttruncates fractional percentages in PostgreSQL and several other engines).
Alternative approaches
- pandas DataFrames: split
posts = df[df.post_type == 'post']andreplies = df[df.post_type == 'reply'], inner-mergerepliesontopostsonpost_parent_id == post_id, then use.groupby('post_id').size()for Metric 1 and.merge(users, how='left')+.groupby('post_author_id')for Metric 2. This expresses the same hash-join logic in vectorized DataFrame calls, with extra import and DataFrame setup overhead on small inputs. - SQL self-join: in an analytical warehouse, both metrics execute directly inside SQL (shown in the first follow-up below), avoiding streaming millions of rows into Python memory.
Follow-up questions
- How would you express both engagement metrics in SQL while preserving authors who only received non-US replies in the denominator? Use a self-join (joining
all_postto itself under two aliases,pfor root posts andrfor direct replies, onr.post_parent_id = p.post_id). Forpct_users, write a CTE (Common Table Expression, a named temporary subquery introduced withWITH) thatINNER JOINsptorso every creator with at least one direct reply is retained, andLEFT JOINs"user"(LEFT JOINpreserves the reply row even when the replier has no matching user record) while checkingu.country = 'US'insideCOUNT(DISTINCT CASE WHEN ...):
```sql -- Metric 1: distinct creators with >= 1 root post receiving >= 2 replies within 7 days SELECT COUNT(DISTINCT busy.post_author_id) AS num_users FROM ( SELECT p.post_id, p.post_author_id FROM all_post AS p JOIN all_post AS r ON r.post_parent_id = p.post_id AND r.post_type = 'reply' AND r.post_creation_time >= p.post_creation_time AND r.post_creation_time <= p.post_creation_time + INTERVAL '7' DAY WHERE p.post_type = 'post' GROUP BY p.post_id, p.post_author_id HAVING COUNT(*) >= 2 ) AS busy;
-- Metric 2: % of replied-to creators with >= 2 distinct US repliers WITH receivers AS ( SELECT p.post_author_id AS author_id, COUNT(DISTINCT CASE WHEN u.country = 'US' THEN r.post_author_id END) AS us_repliers FROM all_post AS p JOIN all_post AS r ON r.post_parent_id = p.post_id AND r.post_type = 'reply' LEFT JOIN "user" AS u ON u.user_id = r.post_author_id WHERE p.post_type = 'post' GROUP BY p.post_author_id ) SELECT COALESCE( 100.0 * SUM(CASE WHEN us_repliers >= 2 THEN 1 ELSE 0 END) / NULLIF(COUNT(*), 0), 0.0 ) AS pct_users FROM receivers; ```
- How would your algorithm change if arbitrarily deep reply threads (replies to replies) also counted toward the root post? First index
parent_of = {row['post_id']: row['post_parent_id']}across all rows, then climb from each reply up to its root'post'iteratively while memoizing results in aroot_ofdictionary (path compression: after walkingr3 -> r2 -> p1, cacheroot_of[r3] = p1androot_of[r2] = p1so subsequent replies underr2resolve inO(1)). Every node is traversed at most twice across the entire dataset, preservingO(P)total time, and in SQL the counterpart is aWITH RECURSIVECTE anchored on root posts. - How should self-replies and automated bot accounts be handled when defining these metrics in production? Under the literal specification every reply row counts, so our code includes them, but in a product analytics review you should call both out explicitly. A creator replying twice to their own thread ("self-bumping") satisfies the 2-reply threshold without genuine audience interaction; filtering
replier_id != post_author_idexcludes self-replies, and joining a bot/human-verification flag onusersprevents automated accounts from inflating engagement metrics.
Follow-up questions
- How would you express both engagement metrics in SQL while preserving authors who only received non-US replies in the denominator?
- How would your algorithm change if arbitrarily deep reply threads (replies to replies) also counted toward the root post?
- How should self-replies and automated bot accounts be handled when defining these metrics in production?
Similar questions
- Detecting and Evaluating Uncredited Reposts
- Job Posting Engagement Metrics Excluding Non-Viewing Applicants
- Compute 7-Day DAU, D1 Retention, and Revenue Cohorts
- Class-Level 2024 Exam Summary with Zero-Filled Averages
- Summarizing Imaging Claims Spend and Fiscal Months
- Build Rolling User Features for Experiment Regression