Social Media Reply Analytics
SQL & DataAuto-graded · 16 test casesLast updated
Analyzes reply patterns in social media data using temporal filtering, joins, and aggregation to compute engagement metrics.
You are building analytics for a social media platform. The platform has posts and replies stored in two data structures:
Data Structures
all_post (list of dictionaries)
Each dictionary represents a post or reply with these keys:
post_id: integer, unique identifierpost_author_id: integer, ID of the user who created this contentpost_creation_time: string (ISO 8601 format with 'Z' suffix) or datetime objectpost_type: string, either'post'(original content) or'reply'(response to another post)post_content: string, the text contentpost_parent_id: integer or None- For replies (
post_type='reply'), this points to thepost_idbeing replied to - For original posts (
post_type='post'), this is None
- For replies (
users (list of dictionaries)
Each dictionary represents a user:
user_id: integer, unique identifierage: integercountry: string (two-letter code like'US','CA')
Your Task
Implement a function that returns a dictionary with two metrics:
Metric 1: num_users
Count how many distinct users authored at least one original post that received 2 or more replies within a 7-day window.
The 7-day window is inclusive on both ends: a reply counts if its post_creation_time falls between the original post's timestamp and that timestamp plus exactly 7 days.
Metric 2: pct_users
Among users who received at least one reply to any of their original posts, calculate what percentage received replies from at least 2 distinct users who are both located in the US (country='US').
- Numerator: count of users whose original posts received replies from 2+ distinct US-based repliers
- Denominator: count of users who received at least one reply to any original post
- Result: percentage as a float between 0 and 100
If no users received any replies, return 0.0 for this metric.
Return Value
A dictionary with two keys:
'num_users': integer'pct_users': float
Constraints
- 1 ≤ len(all_post) ≤ 10,000
- 0 ≤ len(users) ≤ 5,000
- All
post_idvalues are unique - All
user_idvalues are unique - Timestamps are either datetime objects or ISO 8601 strings with 'Z' timezone
- A reply's
post_parent_idmay reference a post not in the dataset (orphan reply) - Users may reply to their own posts
- The same user may reply multiple times to the same post
Examples
Example 1
Input: analyze_reply_metrics([{'post_id': 1, 'post_author_id': 10, 'post_creation_time': '2024-01-01T00:00:00Z', 'post_type': 'post', 'post_content': 'hello', 'post_parent_id': None}, {'post_id': 2, 'post_author_id': 20, 'post_creation_time': '2024-01-02T00:00:00Z', 'post_type': 'reply', 'post_content': 'reply one', 'post_parent_id': 1}, {'post_id': 3, 'post_author_id': 21, 'post_creation_time': '2024-01-08T00:00:00Z', 'post_type': 'reply', 'post_content': 'reply two', 'post_parent_id': 1}, {'post_id': 4, 'post_author_id': 22, 'post_creation_time': '2024-01-09T00:00:00Z', 'post_type': 'reply', 'post_content': 'late', 'post_parent_id': 1}], [{'user_id': 10, 'age': 30, 'country': 'CA'}, {'user_id': 20, 'age': 25, 'country': 'US'}, {'user_id': 21, 'age': 31, 'country': 'US'}, {'user_id': 22, 'age': 28, 'country': 'CA'}])
Output: {'num_users': 1, 'pct_users': 100}
Example 2
Input: analyze_reply_metrics([{'post_id': 1, 'post_author_id': 10, 'post_creation_time': '2024-03-01T12:00:00Z', 'post_type': 'post', 'post_content': 'post', 'post_parent_id': None}, {'post_id': 2, 'post_author_id': 20, 'post_creation_time': '2024-03-01T13:00:00Z', 'post_type': 'reply', 'post_content': 'reply', 'post_parent_id': 1}, {'post_id': 3, 'post_author_id': 10, 'post_creation_time': '2024-03-02T12:00:00Z', 'post_type': 'post', 'post_content': 'another', 'post_parent_id': None}, {'post_id': 4, 'post_author_id': 20, 'post_creation_time': '2024-03-03T12:00:00Z', 'post_type': 'reply', 'post_content': 'reply again', 'post_parent_id': 3}, {'post_id': 5, 'post_author_id': 30, 'post_creation_time': '2024-03-04T12:00:00Z', 'post_type': 'reply', 'post_content': 'reply third', 'post_parent_id': 3}], [{'user_id': 10, 'age': 40, 'country': 'CA'}, {'user_id': 20, 'age': 27, 'country': 'US'}, {'user_id': 30, 'age': 32, 'country': 'US'}])
Output: {'num_users': 1, 'pct_users': 100}
Hints
Hint 1
Build two indexes in a single pass: one mapping each post to its replies, and another mapping each original post author to all replies they received.
Hint 2
For the 7-day window, remember that 'within 7 days' means the reply timestamp must be ≤ original timestamp + 7 days, inclusive.
Hint 3
When counting distinct US repliers, use a set to ensure the same user replying multiple times only counts once.
Worked solution
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The solution builds two indexes in a single pass through the posts, then uses those indexes to compute each metric independently.
Index Construction:
replies_by_post: maps each post ID to the list of replies targeting it (used for metric 1)replies_by_author: maps each original post author to all replies received across their posts (used for metric 2)
When processing a reply, we add it to replies_by_post under its parent ID. We also check if the parent exists and is an original post; if so, we add the reply to replies_by_author under the parent's author ID.
Metric 1 (num_users):
For each original post, parse its timestamp and define the window as [timestamp, timestamp + 7 days]. Count how many replies to that post fall within this window using the replies_by_post index. If the count is at least 2, add the post's author to a set. The size of this set is the answer. Using a set ensures each author is counted once even if they have multiple qualifying posts.
Metric 2 (pct_users):
The denominator is all users who received at least one reply—these are exactly the keys in replies_by_author. For each such user, collect the set of distinct US-based repliers by looking up each replier in the users table and checking their country. If the set size is at least 2, increment the numerator. Divide and multiply by 100 to get the percentage, guarding against division by zero.
Why It Works
- Temporal filtering: The window check
start <= reply_time <= start + 7 dayscorrectly implements "within 7 days inclusive." - Distinct counting: Using sets for both qualifying authors (metric 1) and US repliers (metric 2) ensures correctness when the same entity appears multiple times.
- Only original posts count: Replies to replies are excluded because we only add to
replies_by_authorwhen the parent haspost_type='post'. - Missing users: If a replier's ID is not in the users table, the dictionary
.get()returns None and they are not counted as a US replier.
Complexity
- Time: O(P + U), where P is the number of posts/replies and U is the number of users. We scan all posts once to build indexes, then iterate through posts once more for metric 1 and through recipients once for metric 2.
- Space: O(P + U) for the dictionaries and sets.
Solution Code
from datetime import datetime, timedelta
from typing import Dict, List
def analyze_reply_metrics(all_post, users):
posts_by_id = {row['post_id']: row for row in all_post}
user_by_id = {row['user_id']: row for row in users}
def parse_time(value):
if isinstance(value, datetime):
return value
return datetime.fromisoformat(value.replace('Z', '+00:00'))
replies_by_post = {}
replies_by_author = {}
for row in all_post:
if row['post_type'] == 'reply':
parent_id = row.get('post_parent_id')
replies_by_post.setdefault(parent_id, []).append(row)
parent = posts_by_id.get(parent_id)
if parent is not None and parent['post_type'] == 'post':
replies_by_author.setdefault(parent['post_author_id'], []).append(row)
qualifying_authors = set()
for post in all_post:
if post['post_type'] != 'post':
continue
start = parse_time(post['post_creation_time'])
end = start + timedelta(days=7)
in_window = sum(
1 for reply in replies_by_post.get(post['post_id'], [])
if start <= parse_time(reply['post_creation_time']) <= end
)
if in_window >= 2:
qualifying_authors.add(post['post_author_id'])
received_users = set(replies_by_author)
qualifying_users = 0
for recipient_id in received_users:
us_repliers = {
reply['post_author_id']
for reply in replies_by_author[recipient_id]
if user_by_id.get(reply['post_author_id'], {}).get('country') == 'US'
}
if len(us_repliers) >= 2:
qualifying_users += 1
pct_users = 100.0 * qualifying_users / len(received_users) if received_users else 0.0
return {'num_users': len(qualifying_authors), 'pct_users': pct_users}