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 (str or datetime): 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]): None when post_type == 'post', or the target post_id when post_type == 'reply'. Only direct replies whose post_parent_id references 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:

  1. 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's post_creation_time and at most 7 days (7 * 24 hours, 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.
  2. 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 returning 0.0 when the denominator is 0), compute the percentage (0.0 to 100.0) who received direct replies across all of their root posts combined from at least 2 distinct repliers whose country in users equals '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_post are not guaranteed to be sorted chronologically; a reply may appear before its parent post in the list.
  • Some post_author_id values in all_post may have no corresponding record in users (treat their country as non-'US').
  • The 7-day window in num_users is exact and inclusive on both boundaries: 0 seconds <= reply_time - post_time <= 7 * 86,400 seconds.

Step-by-step walkthrough

  1. Separate the rules for both metrics

    We receive two tables as lists of dictionaries — all_post (storing both root posts and replies) and users — 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 reply
    

    Two rules are especially important: - Nested replies do not count: both metrics examine direct replies to root posts (post_type == 'post'). If Reply 55 has post_parent_id pointing to Reply 52, Reply 55 is ignored by both metrics. - Empty denominator: when zero root posts receive any direct reply, pct_users returns 0.0 rather than dividing by zero.

  2. Why nested loops are slow and how indexing fixes it

    A brute-force scan loops over every root post and searches the entire all_post list to find replies whose post_parent_id matches that post's post_id. With P rows in all_post, that nested scan takes O(P^2) comparisons — billions of steps once P reaches 100,000.

    All that inner loop does is join each reply to its parent post. Storing root posts in a dictionary keyed by post_id drops each parent lookup from O(P) to O(1) average time! Running two linear passes over all_post also handles out-of-order logs where a reply appears before its parent post.

  3. 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-aware datetime objects in UTC (replacing a trailing 'Z' with '+00:00' so datetime.fromisoformat works cleanly across Python versions).

    Then index_posts_and_replies makes two straightforward passes: 1. Pass 1 records every root post (post_type == 'post') in originals[post_id] = (author_id, created_at). 2. Pass 2 collects every 'reply' whose post_parent_id is in originals. That single parent_id in originals check 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_replies
    
  4. Compute Metric 1: count quick replies per post, then deduplicate authors

    Why must we count per post_id before grouping by author_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 increment quick_reply_counts[parent_id]. Both endpoints are inclusive (<=), so a reply arriving at the exact same second or 7 * 24 hours later counts. 2. Add the author of every post with reply_count >= 2 into a set (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)
    
  5. 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 inflating pct_users.

    We track both the denominator and numerator in one dictionary, us_repliers_by_author: - Whenever any direct reply arrives for post_author_id, we ensure us_repliers_by_author[post_author_id] exists (initialized to an empty set()). Thus len(us_repliers_by_author) equals the exact number of distinct replied-to creators. - If replier_id is in us_user_ids (country == 'US'), we add replier_id to us_repliers_by_author[post_author_id]. Because it is a set, 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_receivers
    
  6. Trace Example 1 and Example 2

    Example 1: Root posts are 10 (creator 101, 'DE'), 13 (creator 102, 'US'), and 15 (creator 103, '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.0
    

    Notice that Creator 101 living in 'DE' still qualifies in Metric 2 because only the repliers' countries (201 and 202 in 'US') matter!

    Example 2: Creator 301 publishes root posts 50 and 51: - Reply 55 points to Reply 52 (not in originals), so it is skipped immediately. - Post 50 gets reply 52 (+1 day, in window) and reply 53 (+9 days, outside 7-day window) -> quick_reply_counts[50] = 1. - Post 51 gets reply 54 (+1 day, in window) -> quick_reply_counts[51] = 1. - Metric 1: neither post reaches >= 2, so num_users = 0. - Metric 2: pooling across both posts with no time limit gives us_repliers_by_author[301] = {401, 402} (replier 401 deduplicated, late replier 402 included), so 1 of 1 receiver qualifies and pct_users = 100.0.

  7. 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 scan all_post twice to parse timestamps and pair direct replies (O(P)), scan users once to build us_user_ids (O(U)), and iterate over matched replies with O(1) average-time dictionary and set operations.
  • Space — O(P + U): originals and direct_replies hold at most P entries combined, us_user_ids holds at most U user IDs, and the per-creator replier sets hold at most one entry per reply (<= P).

Edge cases

  • Empty tables or zero replies overall: num_users is 0 and total_receivers == 0 returns pct_users = 0.0 without raising ZeroDivisionError.
  • Exact 7-day boundary: a reply at the exact same second (elapsed == 0) or 7 * 24 hours 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_id points to a 'reply' row): ignored by both metrics because parent_id is absent from originals, 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 in us_repliers_by_author with an empty set so they stay in Metric 2's denominator while contributing 0 to the numerator.
  • Out-of-order input rows: a reply appearing before its parent post in all_post is still matched because originals is 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 50 and 1 quick reply on Post 51 gives 2 replies for Creator 301 even though neither post received >= 2 quick replies.
  • Counting Metric 2 per post instead of per creator: a creator who gets 1 'US' replier on Post 50 and a different 'US' replier on Post 51 has 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 inflating pct_users.
  • Applying the 7-day cutoff to Metric 2: Metric 2 has no time window; filtering by REPLY_WINDOW undercounts both receivers and 'US' repliers.
  • Returning a [0, 1] ratio instead of a [0, 100] percentage, or using integer division in SQL (100 * int / int truncates fractional percentages in PostgreSQL and several other engines).

Alternative approaches

  • pandas DataFrames: split posts = df[df.post_type == 'post'] and replies = df[df.post_type == 'reply'], inner-merge replies onto posts on post_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_post to itself under two aliases, p for root posts and r for direct replies, on r.post_parent_id = p.post_id). For pct_users, write a CTE (Common Table Expression, a named temporary subquery introduced with WITH) that INNER JOINs p to r so every creator with at least one direct reply is retained, and LEFT JOINs "user" (LEFT JOIN preserves the reply row even when the replier has no matching user record) while checking u.country = 'US' inside COUNT(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 a root_of dictionary (path compression: after walking r3 -> r2 -> p1, cache root_of[r3] = p1 and root_of[r2] = p1 so subsequent replies under r2 resolve in O(1)). Every node is traversed at most twice across the entire dataset, preserving O(P) total time, and in SQL the counterpart is a WITH RECURSIVE CTE 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_id excludes self-replies, and joining a bot/human-verification flag on users prevents automated accounts from inflating engagement metrics.

Follow-up questions

Similar questions

More Tools For Humanity interview questions

All 2 Tools For Humanity questions →