Aggregating Safety and Activity Metrics Across Multiple Entities
SQL & DataAuto-graded · 15 test casesLast updated
Tests proficiency in multi-table aggregation, ratio computation, windowed moving averages, and handling edge cases with missing data.
You're analyzing data from a platform with three entities: users, characters (created by users), and conversations (interactions between users and characters).
Given three lists of dictionaries representing these entities, compute five different metrics.
Input Format
users
Each dictionary contains:
user_id: integer, unique identifiercreated_at: string, ISO timestamp
characters
Each dictionary contains:
character_id: integer, unique identifiercreated_by_user_id: integer, references a usercreated_at: string, ISO timestampsafety_flag: boolean (True= safe,False= unsafe)
conversations
Each dictionary contains:
conversation_id: integercharacter_id: integer, references a characteruser_id: integer, references a usercreated_at: string, ISO timestampsafety_flag: boolean (True= safe,False= unsafe)
Note: Multiple conversation entries may share the same conversation_id if multiple users participated.
Output Format
Return a dictionary with five keys:
1. top_characters
List of the 100 characters with the most conversation engagements (conversation rows), ordered by engagement count descending, then by character_id ascending.
Include all characters even if they have zero engagements. If fewer than 100 characters exist, return all of them.
Each entry: {'character_id': int, 'engagement_count': int}
2. unsafe_character_ratio
Float representing the fraction of characters where safety_flag is False.
Return 0.0 if no characters exist.
3. daily_unsafe_character_pct
For each day on which characters were created (extracted as created_at[:10]), compute:
daily_unsafe_pct: fraction of characters created that day withsafety_flag = Falsedaily_unsafe_pct_ma7: 7-day trailing moving average ofdaily_unsafe_pct, computed over the current day and up to 6 prior days that have data
Return a list ordered by day ascending.
Each entry: {'day': str, 'daily_unsafe_pct': float, 'daily_unsafe_pct_ma7': float}
4. safety_breakdown
A 2×2 matrix showing engagement counts categorized by character safety and conversation safety.
Always return exactly 4 entries in this order:
character_safety_flag=False, conversation_safety_flag=Falsecharacter_safety_flag=False, conversation_safety_flag=Truecharacter_safety_flag=True, conversation_safety_flag=Falsecharacter_safety_flag=True, conversation_safety_flag=True
Include entries with count 0. Conversations whose character_id doesn't exist in characters should be ignored.
Each entry: {'character_safety_flag': bool, 'conversation_safety_flag': bool, 'engagement_count': int}
5. daily_unsafe_user_metrics
For each day on which conversations occurred, compute:
unsafe_conversation_engagements: count of conversation rows withsafety_flag = Falseunsafe_users: count of distinct users who participated in at least one unsafe conversation that daytotal_engagements: total conversation rows that daytotal_users: count of distinct users that dayunsafe_engagement_ratio:unsafe_conversation_engagements / total_engagementsunsafe_user_ratio:unsafe_users / total_users
Return a list ordered by day ascending. Days with no conversations are not included.
Each entry: {'day': str, 'unsafe_conversation_engagements': int, 'unsafe_users': int, 'total_engagements': int, 'total_users': int, 'unsafe_engagement_ratio': float, 'unsafe_user_ratio': float}
Constraints
- 0 ≤ len(users) ≤ 10,000
- 0 ≤ len(characters) ≤ 10,000
- 0 ≤ len(conversations) ≤ 100,000
- All timestamps are UTC in ISO 8601 format
character_idanduser_idvalues are positive integers- Days are extracted as the first 10 characters of the timestamp (YYYY-MM-DD format)
Examples
Example 1
Input: aggregate_safety_metrics([], [{'character_id': 1, 'created_by_user_id': 10, 'created_at': '2024-01-01T10:00:00Z', 'safety_flag': True}, {'character_id': 2, 'created_by_user_id': 11, 'created_at': '2024-01-01T10:00:00Z', 'safety_flag': False}, {'character_id': 3, 'created_by_user_id': 10, 'created_at': '2024-01-02T10:00:00Z', 'safety_flag': False}], [{'conversation_id': 100, 'character_id': 1, 'user_id': 20, 'created_at': '2024-01-02T01:00:00Z', 'safety_flag': True}, {'conversation_id': 101, 'character_id': 1, 'user_id': 21, 'created_at': '2024-01-02T02:00:00Z', 'safety_flag': False}, {'conversation_id': 102, 'character_id': 2, 'user_id': 20, 'created_at': '2024-01-02T03:00:00Z', 'safety_flag': False}])
Output: {'top_characters': [{'character_id': 1, 'engagement_count': 2}, {'character_id': 2, 'engagement_count': 1}, {'character_id': 3, 'engagement_count': 0}], 'unsafe_character_ratio': 0.6666666666666666, 'daily_unsafe_character_pct': [{'day': '2024-01-01', 'daily_unsafe_pct': 0.5, 'daily_unsafe_pct_ma7': 0.5}, {'day': '2024-01-02', 'daily_unsafe_pct': 1, 'daily_unsafe_pct_ma7': 0.75}], 'safety_breakdown': [{'character_safety_flag': False, 'conversation_safety_flag': False, 'engagement_count': 1}, {'character_safety_flag': False, 'conversation_safety_flag': True, 'engagement_count': 0}, {'character_safety_flag': True, 'conversation_safety_flag': False, 'engagement_count': 1}, {'character_safety_flag': True, 'conversation_safety_flag': True, 'engagement_count': 1}], 'daily_unsafe_user_metrics': [{'day': '2024-01-02', 'unsafe_conversation_engagements': 2, 'unsafe_users': 2, 'total_engagements': 3, 'total_users': 2, 'unsafe_engagement_ratio': 0.6666666666666666, 'unsafe_user_ratio': 1}]}
Example 2
Input: aggregate_safety_metrics([{'user_id': 1, 'created_at': '2024-01-01T00:00:00Z'}], [{'character_id': 7, 'created_by_user_id': 1, 'created_at': '2024-03-10T12:00:00Z', 'safety_flag': True}], [])
Output: {'top_characters': [{'character_id': 7, 'engagement_count': 0}], 'unsafe_character_ratio': 0, 'daily_unsafe_character_pct': [{'day': '2024-03-10', 'daily_unsafe_pct': 0, 'daily_unsafe_pct_ma7': 0}], 'safety_breakdown': [{'character_safety_flag': False, 'conversation_safety_flag': False, 'engagement_count': 0}, {'character_safety_flag': False, 'conversation_safety_flag': True, 'engagement_count': 0}, {'character_safety_flag': True, 'conversation_safety_flag': False, 'engagement_count': 0}, {'character_safety_flag': True, 'conversation_safety_flag': True, 'engagement_count': 0}], 'daily_unsafe_user_metrics': []}
Hints
Hint 1
For the top characters metric, remember to include characters with zero engagements and handle ties deterministically by character_id.
Hint 2
The 7-day moving average should average the daily percentages themselves, not recompute from pooled counts. Use only days that actually have data.
Hint 3
When computing distinct counts conditionally (like unsafe_users), you can filter first then count distinct, or use conditional logic within the aggregation.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This problem requires computing five distinct aggregation metrics from three related entities. Each metric operates at a different granularity and requires careful handling of edge cases.
Top Characters (Metric 1)
Count conversation rows per character and sort by count descending, breaking ties by character_id ascending. Critically, include all characters even if they have zero engagements—this requires iterating through the characters list separately, not just grouping conversations.
Unsafe Character Ratio (Metric 2)
Compute the fraction of characters flagged as unsafe. Return 0.0 for empty input to avoid division by zero.
Daily Unsafe Percentage with Moving Average (Metric 3)
Group characters by creation day and compute the unsafe fraction for each day. Then apply a 7-day trailing moving average over the daily percentages themselves, not raw counts. The window includes the current day plus up to 6 prior days that have data. For the first few days, the window will be smaller than 7.
Safety Breakdown Matrix (Metric 4)
Create a 2×2 contingency table crossing character safety flags with conversation safety flags. Build a lookup map from character_id to safety_flag, then group conversations by both dimensions. Always output all four cells in the specified order, using 0 for missing combinations.
Daily Unsafe User Metrics (Metric 5)
For each day conversations occur, track both total and unsafe-specific metrics. Maintain sets of user_ids to count distinct users accurately. A user who participates in multiple unsafe conversations on the same day is counted once in unsafe_users.
Why It Works
Each metric is computed at its natural granularity: conversation rows for engagements, character records for character ratios, distinct user IDs for user counts. Sorting is deterministic with explicit tie-breaking rules. The moving average correctly averages percentages rather than pooling counts, which preserves the equal weighting of days regardless of volume.
The 2×2 matrix always outputs exactly four entries by constructing the full cross product of boolean values, ensuring consistent output structure.
Complexity
Let C = number of characters, V = number of conversations, D = number of distinct days.
Time: O(V + C log C + D log D)
- Counting conversations: O(V)
- Sorting characters: O(C log C)
- Grouping by day and sorting days: O(V + D log D)
- Moving average computation: O(7 × D) = O(D)
Space: O(V + C + D)
- Hash maps for grouping: O(C + D)
- Sets for tracking distinct users per day: O(V) worst case
Implementation
from typing import List, Dict
from collections import defaultdict
def aggregate_safety_metrics(users: List[Dict], characters: List[Dict], conversations: List[Dict]) -> Dict:
# Task 1: Top 100 characters by engagement count
engagement_counts = defaultdict(int)
for conv in conversations:
engagement_counts[conv['character_id']] += 1
for char in characters:
if char['character_id'] not in engagement_counts:
engagement_counts[char['character_id']] = 0
top_characters = [
{'character_id': cid, 'engagement_count': count}
for cid, count in engagement_counts.items()
]
top_characters.sort(key=lambda x: (-x['engagement_count'], x['character_id']))
top_characters = top_characters[:100]
# Task 2: Unsafe character ratio
if len(characters) == 0:
unsafe_character_ratio = 0.0
else:
unsafe_count = sum(1 for c in characters if not c['safety_flag'])
unsafe_character_ratio = unsafe_count / len(characters)
# Task 3: Daily unsafe character percentage with 7-day moving average
daily_chars = defaultdict(lambda: {'total': 0, 'unsafe': 0})
for char in characters:
day = char['created_at'][:10]
daily_chars[day]['total'] += 1
if not char['safety_flag']:
daily_chars[day]['unsafe'] += 1
daily_unsafe_pct_list = []
sorted_days = sorted(daily_chars.keys())
for i, day in enumerate(sorted_days):
daily_unsafe_pct = daily_chars[day]['unsafe'] / daily_chars[day]['total']
start_idx = max(0, i - 6)
ma_days = sorted_days[start_idx:i+1]
ma_sum = sum(daily_chars[d]['unsafe'] / daily_chars[d]['total'] for d in ma_days)
daily_unsafe_pct_ma7 = ma_sum / len(ma_days)
daily_unsafe_pct_list.append({
'day': day,
'daily_unsafe_pct': daily_unsafe_pct,
'daily_unsafe_pct_ma7': daily_unsafe_pct_ma7
})
# Task 4a: Safety breakdown (2x2 matrix)
char_safety = {c['character_id']: c['safety_flag'] for c in characters}
breakdown_counts = defaultdict(int)
for conv in conversations:
char_flag = char_safety.get(conv['character_id'])
conv_flag = conv['safety_flag']
breakdown_counts[(char_flag, conv_flag)] += 1
safety_breakdown = []
for char_flag in [False, True]:
for conv_flag in [False, True]:
count = breakdown_counts.get((char_flag, conv_flag), 0)
safety_breakdown.append({
'character_safety_flag': char_flag,
'conversation_safety_flag': conv_flag,
'engagement_count': count
})
# Task 4b: Daily unsafe user metrics
daily_convs = defaultdict(lambda: {
'unsafe_convs': [],
'all_convs': [],
'unsafe_users': set(),
'all_users': set()
})
for conv in conversations:
day = conv['created_at'][:10]
daily_convs[day]['all_convs'].append(conv)
daily_convs[day]['all_users'].add(conv['user_id'])
if not conv['safety_flag']:
daily_convs[day]['unsafe_convs'].append(conv)
daily_convs[day]['unsafe_users'].add(conv['user_id'])
daily_unsafe_user_metrics = []
for day in sorted(daily_convs.keys()):
data = daily_convs[day]
unsafe_conversation_engagements = len(data['unsafe_convs'])
unsafe_users = len(data['unsafe_users'])
total_engagements = len(data['all_convs'])
total_users = len(data['all_users'])
unsafe_engagement_ratio = unsafe_conversation_engagements / total_engagements if total_engagements > 0 else 0
unsafe_user_ratio = unsafe_users / total_users if total_users > 0 else 0
daily_unsafe_user_metrics.append({
'day': day,
'unsafe_conversation_engagements': unsafe_conversation_engagements,
'unsafe_users': unsafe_users,
'total_engagements': total_engagements,
'total_users': total_users,
'unsafe_engagement_ratio': unsafe_engagement_ratio,
'unsafe_user_ratio': unsafe_user_ratio
})
return {
'top_characters': top_characters,
'unsafe_character_ratio': unsafe_character_ratio,
'daily_unsafe_character_pct': daily_unsafe_pct_list,
'safety_breakdown': safety_breakdown,
'daily_unsafe_user_metrics': daily_unsafe_user_metrics
}