Creator Reach Score and Monthly New-Follower Trends
SQL & DataAuto-graded · 16 test casesLast updated
Join and aggregate social-graph records to compute per-user reach scores and per-month follower statistics, including previous-month lookups, growth rates and running totals.
You are given four in-memory "tables" for a social app, each a list of dictionaries. Write a function that computes two reports from them.
Input
accounts: one dict per user, with keyuser_id.articles: one dict per post, with keyspost_idandauthor_id.interactions: one dict per engagement event, with keyspost_id,viewer_idandevent_type(for examplelike,comment,share).connections: one dict per follow relationship, with keysfollower_id,followee_idandcreated_at.created_atis a UTC timestamp, normally an ISO-8601 string such as"2024-01-05T12:00:00Z". Adatetimeobject may also appear.
The month of a follow is its created_at formatted as "YYYY-MM".
Report 1: reach score
For every user in accounts, the reach score is:
reach = (number of interaction events on posts written by the user) + (number of distinct followers of the user)
- Every event counts once, whatever its
event_type. - An event whose
post_iddoes not appear inarticlesis ignored. - Followers are counted by distinct
follower_idamong the rows wherefollowee_idis the user, so repeated follow rows from the same person count once. - Self-follows and self-engagement are counted like any other.
- Users with no posts or followers get a score of
0.
Return one entry per user in accounts, as {"user_id": ..., "influence_score": ...}, sorted by user_id ascending.
Report 2: monthly follower trends
Group connections by (followee_id, month). For each group, produce a row with:
month: the"YYYY-MM"string.followee_id.new_followers: the number of distinctfollower_idvalues in that group.prev_month_new_followers: thenew_followersof that followee's previous row in time order, orNonefor the followee's first row. "Previous" means the previous month that has at least one follow row. Calendar gaps are not filled with zeros.mom_growth:(new_followers - prev_month_new_followers) / prev_month_new_followersas a float, orNonewhen there is no previous row or the previous value is0.cumulative_followers: the sum ofnew_followersover this row and all earlier rows of the same followee. This is a plain running sum of the monthly counts, so a person who follows in two different months is counted in both.
Report 2 is built from connections alone. It does not depend on accounts. Sort the rows by followee_id ascending, then by month ascending.
Output
Return a dict with two keys:
{"influence": [...report 1 rows...], "monthly_growth": [...report 2 rows...]}
Constraints
- All four lists may be empty. Then both reports are empty lists.
- Assume
user_idvalues inaccountsare unique. - Follows are never undone, so there are no unfollow events.
- Input sizes are modest, so one pass over each list with hash maps is enough.
Examples
Example 1
Input: compute_creator_metrics([{'user_id': 1}, {'user_id': 2}, {'user_id': 3}], [{'post_id': 10, 'author_id': 1}, {'post_id': 11, 'author_id': 2}], [{'post_id': 10, 'viewer_id': 2, 'event_type': 'like'}, {'post_id': 10, 'viewer_id': 3, 'event_type': 'comment'}, {'post_id': 11, 'viewer_id': 1, 'event_type': 'like'}], [{'follower_id': 2, 'followee_id': 1, 'created_at': '2024-01-05T12:00:00Z'}, {'follower_id': 3, 'followee_id': 1, 'created_at': '2024-02-02T09:00:00Z'}, {'follower_id': 2, 'followee_id': 1, 'created_at': '2024-02-10T10:00:00Z'}])
Output: {'influence': [{'user_id': 1, 'influence_score': 4}, {'user_id': 2, 'influence_score': 1}, {'user_id': 3, 'influence_score': 0}], 'monthly_growth': [{'month': '2024-01', 'followee_id': 1, 'new_followers': 1, 'prev_month_new_followers': None, 'mom_growth': None, 'cumulative_followers': 1}, {'month': '2024-02', 'followee_id': 1, 'new_followers': 2, 'prev_month_new_followers': 1, 'mom_growth': 1, 'cumulative_followers': 3}]}
Example 2
Input: compute_creator_metrics([], [], [], [])
Output: {'influence': [], 'monthly_growth': []}
Example 3
Input: compute_creator_metrics([{'user_id': 5}], [{'post_id': 7, 'author_id': 5}], [{'post_id': 7, 'viewer_id': 5, 'event_type': 'like'}], [{'follower_id': 5, 'followee_id': 5, 'created_at': '2023-12-31T23:59:59Z'}])
Output: {'influence': [{'user_id': 5, 'influence_score': 2}], 'monthly_growth': [{'month': '2023-12', 'followee_id': 5, 'new_followers': 1, 'prev_month_new_followers': None, 'mom_growth': None, 'cumulative_followers': 1}]}
Hints
Hint 1
Build a lookup from post_id to author_id first. Then each interaction can be credited to an author in O(1), and interactions on unknown posts are skipped.
Hint 2
Use a set of follower ids per followee for the follower count, and a second set per (followee, month) for the monthly count, so repeated follow rows are not counted twice.
Hint 3
For the monthly report, group the (month, count) pairs by followee and sort them by month. Walk through them while keeping the previous count and a running total. The growth rate is None when there is no previous value.
Worked solution
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Both reports follow the same pattern: aggregate each source down to one row per key, then combine.
Report 1 (reach score)
- Build a
post_id -> author_idmap fromarticles. - Walk through
interactions. If the post is known, add 1 to its author's received-event counter. Unknown posts are skipped, like an inner join. - Walk through
connectionsand add each follower to a set keyed by followee. The set size is the distinct follower count. - For each account, the score is
received[user] + len(followers[user]), with missing entries treated as 0. This matches aLEFT JOINfrom the users table withCOALESCE(..., 0). - Sort by
user_id.
Report 2 (monthly trends)
- While walking through
connections, also add each follower to a set keyed by(followee, month). The month is the first seven characters of the timestamp, orstrftime('%Y-%m')for adatetime. - Group the
(month, distinct count)pairs by followee and sort them by month. Since"YYYY-MM"strings sort chronologically, string ordering is enough. - Walk each followee's list while keeping the previous count and a running total. These play the roles of
LAGand a cumulativeSUM. - The growth rate is
Nonewhen there is no previous row. It would also beNonefor a previous value of 0, which cannot occur here because every group has at least one follower. - Sort the final rows by
(followee_id, month).
Why it is correct
- Counting through the post-to-author map is equivalent to joining interactions to posts. Each event is counted exactly once, with no multiplication between events and followers, because the two counts are computed separately and only added at the end.
- Sets remove duplicate follow rows, both overall and within a month.
- After sorting, each followee's months are in chronological order. The previous row is therefore the previous active month, and the running total is the sum of everything up to the current month.
Complexity
Let A, P, I, C be the sizes of the four inputs and G the number of (followee, month) groups.
- Time: O(A + P + I + C + G log G + A log A). The log factors come from the sorts.
- Space: O(A + P + C) for the maps and sets, plus O(G) for the output.
Reference solution
from collections import Counter
from datetime import datetime
from typing import Dict, List
def compute_creator_metrics(accounts: List[Dict], articles: List[Dict],
interactions: List[Dict], connections: List[Dict]) -> Dict:
author_of = {a['post_id']: a['author_id'] for a in articles}
received = Counter()
for ev in interactions:
author = author_of.get(ev['post_id'])
if author is not None:
received[author] += 1
followers_by_user = {}
followers_by_month = {}
for c in connections:
followee = c['followee_id']
follower = c['follower_id']
followers_by_user.setdefault(followee, set()).add(follower)
ts = c['created_at']
if isinstance(ts, datetime):
month = ts.strftime('%Y-%m')
else:
month = str(ts)[:7]
followers_by_month.setdefault((followee, month), set()).add(follower)
influence = [
{
'user_id': acc['user_id'],
'influence_score': received[acc['user_id']]
+ len(followers_by_user.get(acc['user_id'], set())),
}
for acc in accounts
]
influence.sort(key=lambda row: row['user_id'])
per_followee = {}
for (followee, month), people in followers_by_month.items():
per_followee.setdefault(followee, []).append((month, len(people)))
growth = []
for followee, months in per_followee.items():
months.sort(key=lambda item: item[0])
previous = None
running = 0
for month, count in months:
running += count
rate = None if previous in (None, 0) else (count - previous) / previous
growth.append({
'month': month,
'followee_id': followee,
'new_followers': count,
'prev_month_new_followers': previous,
'mom_growth': rate,
'cumulative_followers': running,
})
previous = count
growth.sort(key=lambda row: (row['followee_id'], row['month']))
return {'influence': influence, 'monthly_growth': growth}