User Signup and Follower Metrics Report
SQL & DataAuto-graded · 15 test casesLast updated
Simulate three SQL analytics queries in Python: total users, busiest signup month (with tie-break), and the most-followed usernames including ties.
You are given a snapshot of data for a fictional social app, already loaded into Python instead of a database:
users: a list of dictionaries, each with keys"user_id"(int),"username"(str), and"created_at"(a timestamp string of the form"YYYY-MM-DD HH:MM:SS"). Eachuser_idappears at most once.follows: a list of dictionaries, each with keys"follower_user_id"(int) and"followed_user_id"(int). A row means the follower follows the followed user. Rows may repeat, may reference IDs that do not exist inusers, and may be self-follows (follower equals followed).
Write a function user_metrics(users, follows) that returns a dict with exactly these keys:
"user_count": the number of rows inusers."busiest_month": the calendar month (as a string"YYYY-MM"obtained from the first seven characters ofcreated_at) in which the largest number of users signed up. If several months tie for the largest count, choose the lexicographically smallest such month string. Ifusersis empty, this isNone."busiest_month_count": the number of signups in"busiest_month". Ifusersis empty, this is0."most_followed_usernames": a list, sorted in ascending lexicographic order, of the usernames of all users whose follower count equals the maximum follower count. A user's follower count is the number offollowsrows whosefollowed_user_idequals that user'suser_id(duplicates count separately). Users with 0 followers are eligible only when the table is non-empty and no one has any followers. Ifusersis empty, this is an empty list.
Every user present in users is considered, including those with no followers. Follow rows pointing at IDs not in users are ignored for follower counting.
Examples
Example 1
Input: user_metrics([{'user_id': 1, 'username': 'amy', 'created_at': '2024-01-15 10:00:00'}, {'user_id': 2, 'username': 'ben', 'created_at': '2024-02-01 09:00:00'}, {'user_id': 3, 'username': 'cy', 'created_at': '2024-02-18 12:00:00'}], [{'follower_user_id': 1, 'followed_user_id': 2}, {'follower_user_id': 3, 'followed_user_id': 2}, {'follower_user_id': 2, 'followed_user_id': 1}])
Output: {'user_count': 3, 'busiest_month': '2024-02', 'busiest_month_count': 2, 'most_followed_usernames': ['ben']}
Example 2
Input: user_metrics([{'user_id': 1, 'username': 'zoe', 'created_at': '2023-05-01 00:00:00'}, {'user_id': 2, 'username': 'amy', 'created_at': '2024-05-01 00:00:00'}], [])
Output: {'user_count': 2, 'busiest_month': '2023-05', 'busiest_month_count': 1, 'most_followed_usernames': ['amy', 'zoe']}
Hints
Hint 1
Build a frequency dict from the first seven characters of each created_at string; the answer month is the key with the highest count, breaking ties by the smallest key.
Hint 2
Initialize every known user to a follower count of 0 before tallying, so users nobody follows still participate in the maximum.
Hint 3
When follows is empty, all users tie at zero followers, so every username should appear in sorted order.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Walk the user list once, tallying each user's signup month (the first seven characters of created_at) into a counter. The busiest month is the key with the largest tally, with ties resolved by the smaller month string; an empty user list yields None and 0.
For follower counts, build a dictionary that maps every user ID to 0, so users nobody follows still appear. Then iterate the follow rows and increment the count only for targets that exist in that dictionary — unknown IDs are silently skipped and self-follows still count, matching the given data rules.
Finally, take the maximum follower value (when at least one user exists), gather the usernames of every user hitting that maximum, and sort them. Users who tie include the case where everyone has zero followers, which happens naturally because the maximum is then 0.
Correctness: every signup is counted exactly once within its month, and the tie-break min(key=(-count, month)) selects the highest count with the smallest month string. The follower dictionary is seeded with all known users and incremented once per matching follow row, so it equals the true follower count per user, and filtering by equality with the maximum (then sorting) reproduces the required list.
Complexity: let U be the number of users, F the number of follow rows, and M the number of distinct months. Time is O(U + F + U log U) for the sort, space is O(U + M).
from collections import Counter
from typing import Dict, List
def user_metrics(users: List[Dict], follows: List[Dict]) -> Dict:
month_counts = Counter()
for user in users:
month_counts[str(user["created_at"])[:7]] += 1
if month_counts:
busiest_month = min(month_counts, key=lambda m: (-month_counts[m], m))
busiest_month_count = month_counts[busiest_month]
else:
busiest_month = None
busiest_month_count = 0
user_ids = {user["user_id"] for user in users}
follower_counts = {user_id: 0 for user_id in user_ids}
for follow in follows:
target = follow["followed_user_id"]
if target in follower_counts:
follower_counts[target] += 1
if user_ids:
top = max(follower_counts.values())
usernames = sorted(
user["username"]
for user in users
if follower_counts[user["user_id"]] == top
)
else:
usernames = []
return {
"user_count": len(users),
"busiest_month": busiest_month,
"busiest_month_count": busiest_month_count,
"most_followed_usernames": usernames,
}