Character Safety and Engagement Analytics
Medium · Data Manipulation (SQL/Python) · Data Scientist · Technical Screen
Problem Statement
An interactive AI chat service logs three datasets—users, characters, and conversations—with all timestamps recorded in UTC (YYYY-MM-DDTHH:MM:SSZ or YYYY-MM-DD HH:MM:SS). A calendar day is the UTC date prefix YYYY-MM-DD (DATE(created_at) in SQL). On both characters and conversations, safety_flag = True (TRUE) indicates a safe record, safety_flag = False (FALSE) indicates an unsafe record, and None (NULL) is treated as unknown (not unsafe, though still counted in row totals).
Input Tables
usersuser_id(int/BIGINT): unique account identifier.created_at(str/TIMESTAMP): UTC account creation timestamp.
characterscharacter_id(int/BIGINT): unique persona identifier.created_by_user_id(int/BIGINT): creator'suser_id.created_at(str/TIMESTAMP): UTC persona creation timestamp.safety_flag(Optional[bool]/BOOLEAN): persona moderation status.
conversationsconversation_id(int/BIGINT): chat thread identifier (may repeat across multiple rows when more than one user participates in the same thread; every row counts as a separate engagement).character_id(int/BIGINT): referenced persona identifier.user_id(int/BIGINT): participating account identifier.created_at(str/TIMESTAMP): UTC engagement timestamp.safety_flag(Optional[bool]/BOOLEAN): engagement moderation status.
Write SQL queries for the five reporting views below and implement
def compute_character_safety_engagement_metrics(
users: List[Dict], characters: List[Dict], conversations: List[Dict]
) -> Dict:
returning a dictionary with these five keys:
"top_characters"— Up to100personas ranked by total matching rows inconversationsacross all time (engagement_countdescending, breaking ties bycharacter_idascending). Personas with zero engagements must still be eligible withengagement_count = 0. Each list element is{"character_id": int, "engagement_count": int}."unsafe_character_ratio"— Afloatin[0.0, 1.0]giving the share of rows incharacterswheresafety_flagisFalse(return0.0whencharactersis empty)."daily_unsafe_character_pct"— One summary row per UTCdayon which at least one persona was created, sorted bydayascending. Each element is{"day": str, "daily_unsafe_pct": float, "daily_unsafe_pct_ma7": float}, where:daily_unsafe_pctis(# unsafe personas created on day) / (total personas created on day).daily_unsafe_pct_ma7is the unweighted mean ofdaily_unsafe_pctover all active creation days falling inside the 7-calendar-day window[day - 6 days, day]inclusive (in SQL, round both columns to 4 decimal places; in Python, return unrounded floats).
"safety_breakdown"— A 4-row2 x 2contingency table joiningconversationstocharactersoncharacter_idand counting engagements across boolean pairs(character_safety_flag, conversation_safety_flag). Always emit all four boolean pairs in ascending order(False, False),(False, True),(True, False),(True, True)withengagement_count = 0when a pair has no matches:{"character_safety_flag": bool, "conversation_safety_flag": bool, "engagement_count": int}."daily_unsafe_user_metrics"— One row per UTCdaypresent inconversations, sorted bydayascending, containing:"day":YYYY-MM-DDstring,"unsafe_conversation_engagements": rows that day withsafety_flag == False,"unsafe_users": distinctuser_idvalues with at least onesafety_flag == Falserow that day,"total_engagements": all conversation rows that day,"total_users": distinctuser_idvalues across all conversation rows that day,"unsafe_engagement_ratio":unsafe_conversation_engagements / total_engagements,"unsafe_user_ratio":unsafe_users / total_users.
Examples
Example 1
Input:
users = [
{"user_id": 501, "created_at": "2025-04-01T08:00:00Z"},
{"user_id": 502, "created_at": "2025-04-02T09:30:00Z"},
{"user_id": 503, "created_at": "2025-04-03T11:00:00Z"},
]
characters = [
{"character_id": 10, "created_by_user_id": 501, "created_at": "2025-04-10T09:00:00Z", "safety_flag": True},
{"character_id": 20, "created_by_user_id": 502, "created_at": "2025-04-10T14:00:00Z", "safety_flag": False},
{"character_id": 30, "created_by_user_id": 501, "created_at": "2025-04-11T11:00:00Z", "safety_flag": False},
{"character_id": 40, "created_by_user_id": 502, "created_at": "2025-04-13T16:00:00Z", "safety_flag": False},
]
conversations = [
{"conversation_id": 901, "character_id": 10, "user_id": 501, "created_at": "2025-04-13T18:00:00Z", "safety_flag": True},
{"conversation_id": 902, "character_id": 20, "user_id": 502, "created_at": "2025-04-13T19:00:00Z", "safety_flag": False},
{"conversation_id": 903, "character_id": 10, "user_id": 501, "created_at": "2025-04-14T09:00:00Z", "safety_flag": True},
{"conversation_id": 903, "character_id": 10, "user_id": 503, "created_at": "2025-04-14T09:05:00Z", "safety_flag": False},
{"conversation_id": 904, "character_id": 20, "user_id": 503, "created_at": "2025-04-14T11:00:00Z", "safety_flag": True},
{"conversation_id": 905, "character_id": 30, "user_id": 502, "created_at": "2025-04-14T15:00:00Z", "safety_flag": False},
]
Output:
{
"top_characters": [
{"character_id": 10, "engagement_count": 3},
{"character_id": 20, "engagement_count": 2},
{"character_id": 30, "engagement_count": 1},
{"character_id": 40, "engagement_count": 0},
],
"unsafe_character_ratio": 0.75,
"daily_unsafe_character_pct": [
{"day": "2025-04-10", "daily_unsafe_pct": 0.5, "daily_unsafe_pct_ma7": 0.5},
{"day": "2025-04-11", "daily_unsafe_pct": 1.0, "daily_unsafe_pct_ma7": 0.75},
{"day": "2025-04-13", "daily_unsafe_pct": 1.0, "daily_unsafe_pct_ma7": 0.8333333333333334},
],
"safety_breakdown": [
{"character_safety_flag": False, "conversation_safety_flag": False, "engagement_count": 2},
{"character_safety_flag": False, "conversation_safety_flag": True, "engagement_count": 1},
{"character_safety_flag": True, "conversation_safety_flag": False, "engagement_count": 1},
{"character_safety_flag": True, "conversation_safety_flag": True, "engagement_count": 2},
],
"daily_unsafe_user_metrics": [
{
"day": "2025-04-13",
"unsafe_conversation_engagements": 1,
"unsafe_users": 1,
"total_engagements": 2,
"total_users": 2,
"unsafe_engagement_ratio": 0.5,
"unsafe_user_ratio": 0.5,
},
{
"day": "2025-04-14",
"unsafe_conversation_engagements": 2,
"unsafe_users": 2,
"total_engagements": 4,
"total_users": 3,
"unsafe_engagement_ratio": 0.5,
"unsafe_user_ratio": 0.6666666666666666,
},
],
}
Explanation: Both rows sharing conversation_id = 903 count toward character_id = 10, while character_id = 40 stays in top_characters with 0 engagements. Three of four personas are unsafe (0.75). No personas are created on 2025-04-12, so 2025-04-13 averages the three active rates in [2025-04-07, 2025-04-13]: (0.5 + 1.0 + 1.0) / 3 = 5/6. On 2025-04-14, three distinct users (501, 502, 503) generate 4 rows, and two of them (502, 503) have unsafe engagements (2/3).
Example 2
Input:
users = [{"user_id": 801, "created_at": "2025-08-01 08:00:00"}]
characters = [
{"character_id": 50, "created_by_user_id": 801, "created_at": "2025-08-01 09:00:00", "safety_flag": False},
{"character_id": 60, "created_by_user_id": 801, "created_at": "2025-08-10 15:30:00", "safety_flag": True},
]
conversations = [
{"conversation_id": 300, "character_id": 50, "user_id": 801, "created_at": "2025-08-01 12:00:00", "safety_flag": True},
]
Output:
{
"top_characters": [
{"character_id": 50, "engagement_count": 1},
{"character_id": 60, "engagement_count": 0},
],
"unsafe_character_ratio": 0.5,
"daily_unsafe_character_pct": [
{"day": "2025-08-01", "daily_unsafe_pct": 1.0, "daily_unsafe_pct_ma7": 1.0},
{"day": "2025-08-10", "daily_unsafe_pct": 0.0, "daily_unsafe_pct_ma7": 0.0},
],
"safety_breakdown": [
{"character_safety_flag": False, "conversation_safety_flag": False, "engagement_count": 0},
{"character_safety_flag": False, "conversation_safety_flag": True, "engagement_count": 1},
{"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": [
{
"day": "2025-08-01",
"unsafe_conversation_engagements": 0,
"unsafe_users": 0,
"total_engagements": 1,
"total_users": 1,
"unsafe_engagement_ratio": 0.0,
"unsafe_user_ratio": 0.0,
},
],
}
Explanation: By 2025-08-10, the 7-calendar-day window [2025-08-04, 2025-08-10] no longer includes 2025-08-01, so daily_unsafe_pct_ma7 is 0.0. Only (False, True) has a matching conversation, while the other three safety_breakdown cells remain 0.
Constraints
0 <= len(users), len(characters), len(conversations) <= 10^5- Every
created_atstring starts with an ISO UTC calendar dateYYYY-MM-DD(YYYY-MM-DDTHH:MM:SSZorYYYY-MM-DD HH:MM:SS). character_idvalues incharactersare unique.safety_flagisTrue,False, orNone; onlyFalsecounts as unsafe.- Days with zero created characters do not appear in
daily_unsafe_character_pct, and days with zero conversations do not appear indaily_unsafe_user_metrics.
Step-by-step walkthrough
Understand the schema, return shape, and metric rules
We have three product tables (
users,characters,conversations) wheresafety_flag = TRUEmeans safe andsafety_flag = FALSEmeans unsafe, and timestamps are in UTC. We will write the clean SQL query for each of the five analytics tasks and implement the Python judge functioncompute_character_safety_engagement_metrics(users, characters, conversations), which returns one dictionary combining all five results:Output dictionary keys: "top_characters" -> View 1: [{character_id, engagement_count}, ...] (up to 100) "unsafe_character_ratio" -> View 2: float in [0, 1] "daily_unsafe_character_pct" -> View 3: [{day, daily_unsafe_pct, daily_unsafe_pct_ma7}, ...] "safety_breakdown" -> View 4: 4 rows of {character_safety_flag, conversation_safety_flag, engagement_count} "daily_unsafe_user_metrics" -> View 5: [{day, unsafe_conversation_engagements, unsafe_users, ...}, ...]Before coding, note four critical rules confirmed by the specification and examples: 1. Zero-engagement characters stay in view 1: Example 1 includes character
40withengagement_count: 0, so we must start fromcharacters(LEFT JOIN), notconversations. 2. View 3 averages daily percentages over a 7-calendar-day window: Example 1 averages Apr 10 (0.5), Apr 11 (1.0), and Apr 13 (1.0) to(0.5 + 1.0 + 1.0) / 3 = 5/6(mean of daily rates over active days in[day - 6, day], not pooled character counts3/4 = 0.75). 3. View 4 always outputs all four(False/True, False/True)rows: Even when a cell has0conversations (Example 2), it stays in the output. 4. Rounding: The SQL query for view 3 rounds percentages to 4 decimal places (ROUND(..., 4)), while the Python judge expects unrounded floats.Let's start with two tiny Python helpers for SQL-style
FALSEchecks and UTC date extraction:from typing import Optional def is_unsafe(flag: Optional[bool]) -> bool: """Mirror SQL `safety_flag = FALSE`: False is unsafe; True and None (NULL) are not.""" # Checking `flag is not None` first prevents `not None` (which is True in Python!) # from misclassifying missing NULL flags as unsafe. return flag is not None and not flag def utc_day_of(timestamp: str) -> str: """Extract the 'YYYY-MM-DD' UTC calendar date from an ISO timestamp string.""" # Both '2025-04-10T09:00:00Z' and '2025-08-01 09:00:00' begin with 'YYYY-MM-DD'. return timestamp[:10]View 1: Top 100 characters by conversation engagements
Each row in
conversationscounts as one engagement (even if multiple users share the sameconversation_id). To keep characters with zero engagements, we use a LEFT JOIN (a join that keeps every row from the left tablecharactersand fills unmatched columns fromconversationswithNULL).Pay close attention to
COUNT(cv.character_id)vsCOUNT(*): for a character with zero conversations,LEFT JOINstill produces one row withcv.character_id = NULL.COUNT(*)would count that row as1, whereasCOUNT(cv.character_id)ignoresNULLs and rightly returns0!-- LEFT JOIN keeps characters with zero conversations; COUNT(cv.character_id) skips NULLs to yield 0. SELECT ch.character_id, COUNT(cv.character_id) AS engagement_count FROM characters AS ch LEFT JOIN conversations AS cv ON cv.character_id = ch.character_id GROUP BY ch.character_id -- Tie-break by character_id ASC so the top-100 cutoff is deterministic. ORDER BY engagement_count DESC, ch.character_id ASC LIMIT 100;In Python, we seed every character's counter at
0, add1per matching conversation row, and sort(-count, character_id):from typing import Any, Dict, List def top_characters( characters: List[Dict], conversations: List[Dict], limit: int = 100 ) -> List[Dict]: # engagement_count: dict[character_id, int] seeded at 0 for every character (SQL LEFT JOIN) engagement_count: Dict[Any, int] = {} for character in characters: engagement_count[character["character_id"]] = 0 for conversation in conversations: character_id = conversation["character_id"] if character_id in engagement_count: engagement_count[character_id] += 1 # Sort by (-count, character_id) so highest counts come first and ties break deterministically. ranked = [] for character_id, count in engagement_count.items(): ranked.append((-count, character_id)) ranked.sort() rows = [] for negative_count, character_id in ranked[:limit]: rows.append({"character_id": character_id, "engagement_count": -negative_count}) return rowsView 2: Overall unsafe character ratio
The fraction of rows satisfying a condition equals the average of a
1.0/0.0indicator column. Using conditional aggregation (placingCASE WHEN ... ENDinsideAVG) computes the ratio in one pass, and writing floating-point1.0and0.0avoids integer-division truncation (2 / 3 -> 0).-- Map unsafe rows to 1.0 and all other rows to 0.0 so AVG() equals (# unsafe) / (total characters). SELECT AVG(CASE WHEN safety_flag = FALSE THEN 1.0 ELSE 0.0 END) AS unsafe_character_ratio FROM characters;In Python, we guard against an empty
characterslist (returning0.0) and divide unsafe characters bylen(characters):from typing import Dict, List def unsafe_character_ratio(characters: List[Dict]) -> float: if not characters: return 0.0 unsafe_count = 0 for character in characters: if is_unsafe(character["safety_flag"]): unsafe_count += 1 return unsafe_count / len(characters)View 3: 7-day calendar moving average of daily unsafe percentage
First, group
charactersbyDATE(created_at)inside a CTE (Common Table Expression — a named temporary table defined withWITHso later steps can query it cleanly). Next, for each dayd, averagedaily_unsafe_pctover all active days in the 7-calendar-day interval[d - 6 days, d].Watch out for the classic SQL window trap: writing
OVER (ORDER BY day ROWS BETWEEN 6 PRECEDING AND CURRENT ROW)averages the last 7 rows, not the last 7 calendar days! Look at Example 1 (2025-04-12missing) and Example 2 (2025-08-01vs2025-08-10):Example 1 dates: Apr 10 Apr 11 (Apr 12 missing!) Apr 13 daily_unsafe_pct: 0.50 1.00 --- 1.00 7-calendar-day window ending Apr 13 = [Apr 07 .. Apr 13] -> 3 active days: (0.50 + 1.00 + 1.00) / 3 = 0.8333 Example 2 dates: Aug 01 (1.00) ...9 days apart... Aug 10 (0.00) Window [Aug 04 .. Aug 10] excludes Aug 01 -> ma7 = 0.00 (ROWS 6 PRECEDING would give 0.50!)Joining
daily AS dtodaily AS wonw.day BETWEEN DATE(d.day, '-6 days') AND d.dayobeys true calendar dates in SQLite (and in PostgreSQL withd.day - INTERVAL '6 days'):-- Step 1: Compute one row per UTC day that has created characters. WITH daily AS ( SELECT DATE(created_at) AS day, AVG(CASE WHEN safety_flag = FALSE THEN 1.0 ELSE 0.0 END) AS daily_unsafe_pct FROM characters GROUP BY DATE(created_at) ) -- Step 2: Self-join each day `d` to active days `w` within the trailing 7 calendar days [d - 6, d]. SELECT d.day, ROUND(d.daily_unsafe_pct, 4) AS daily_unsafe_pct, ROUND(AVG(w.daily_unsafe_pct), 4) AS daily_unsafe_pct_ma7 FROM daily AS d JOIN daily AS w ON w.day BETWEEN DATE(d.day, '-6 days') AND d.day GROUP BY d.day, d.daily_unsafe_pct ORDER BY d.day ASC;In Python, ISO
'YYYY-MM-DD'strings sort chronologically, so from each daydays[i]we walk backward (j = i, i - 1, ...) whiledays[j] >= (date - 6 days). Since dates indaysare unique, that inner loop takes at most 7 steps:from typing import Dict, List from datetime import date, timedelta def daily_unsafe_character_pct(characters: List[Dict]) -> List[Dict]: # Phase 1: Aggregate total and unsafe created characters per UTC day. total_by_day: Dict[str, int] = {} unsafe_by_day: Dict[str, int] = {} for character in characters: day = utc_day_of(character["created_at"]) total_by_day[day] = total_by_day.get(day, 0) + 1 if is_unsafe(character["safety_flag"]): unsafe_by_day[day] = unsafe_by_day.get(day, 0) + 1 # ISO 'YYYY-MM-DD' strings sort in exact chronological order. days = sorted(total_by_day) pct_by_day: Dict[str, float] = {} for day in days: pct_by_day[day] = unsafe_by_day.get(day, 0) / total_by_day[day] # Phase 2: For each active day, average daily_unsafe_pct across active days in [day - 6, day]. rows = [] for i, day in enumerate(days): window_start = (date.fromisoformat(day) - timedelta(days=6)).isoformat() # Because `days` has unique dates, walking backward inside a 7-day span takes <= 7 steps. window_sum = 0.0 window_days = 0 j = i while j >= 0 and days[j] >= window_start: window_sum += pct_by_day[days[j]] window_days += 1 j -= 1 rows.append({ "day": day, "daily_unsafe_pct": pct_by_day[day], "daily_unsafe_pct_ma7": window_sum / window_days, }) return rowsView 4: Complete 2x2 character-vs-conversation safety breakdown
We want all four cells of the 2x2 table comparing
characters.safety_flagagainstconversations.safety_flag:conversation_safety_flag FALSE TRUE character FALSE (False, False) (False, True) safety TRUE (True, False) (True, True)A plain
GROUP BYomits any cell that happens to have zero matching conversations. To guarantee all 4 rows appear with0when empty, we build the 4 boolean pairs with aCROSS JOINandLEFT JOINthe joined engagements onto them:WITH flag_values AS ( SELECT FALSE AS flag UNION ALL SELECT TRUE ), -- Generate all 4 (character_safety_flag, conversation_safety_flag) combinations. cells AS ( SELECT c.flag AS character_safety_flag, v.flag AS conversation_safety_flag FROM flag_values AS c CROSS JOIN flag_values AS v ), engagements AS ( SELECT ch.safety_flag AS character_safety_flag, cv.safety_flag AS conversation_safety_flag FROM conversations AS cv JOIN characters AS ch ON ch.character_id = cv.character_id ) -- LEFT JOIN onto `cells` and count a right-side column so empty combinations report 0. SELECT cl.character_safety_flag, cl.conversation_safety_flag, COUNT(e.character_safety_flag) AS engagement_count FROM cells AS cl LEFT JOIN engagements AS e ON e.character_safety_flag = cl.character_safety_flag AND e.conversation_safety_flag = cl.conversation_safety_flag GROUP BY cl.character_safety_flag, cl.conversation_safety_flag ORDER BY cl.character_safety_flag ASC, cl.conversation_safety_flag ASC;In Python, we pre-seed
count_by_cellwith all four(False/True, False/True)tuples set to0and look up each conversation's character inO(1)via a dictionary:from typing import Any, Dict, List, Optional def safety_breakdown(characters: List[Dict], conversations: List[Dict]) -> List[Dict]: # flag_by_character: dict[character_id, Optional[bool]] for O(1) inner-join lookup flag_by_character: Dict[Any, Optional[bool]] = {} for character in characters: flag_by_character[character["character_id"]] = character["safety_flag"] # Seed all four (character_flag, conversation_flag) combinations at 0 so empty cells stay visible. cells = [(False, False), (False, True), (True, False), (True, True)] count_by_cell = {cell: 0 for cell in cells} for conversation in conversations: character_id = conversation["character_id"] if character_id not in flag_by_character: continue cell = (flag_by_character[character_id], conversation["safety_flag"]) # A None flag on either side matches none of the four boolean cells, mirroring SQL JOIN. if cell in count_by_cell: count_by_cell[cell] += 1 rows = [] for character_flag, conversation_flag in cells: rows.append({ "character_safety_flag": character_flag, "conversation_safety_flag": conversation_flag, "engagement_count": count_by_cell[(character_flag, conversation_flag)], }) return rowsView 5: Daily unsafe engagements and distinct unsafe users
View 5 needs both unsafe counts and all-conversation totals per day from
conversations. Do not writeWHERE safety_flag = FALSE— that would filter out safe conversations and ruintotal_engagementsandtotal_users!Instead, use conditional aggregation inside
SUM(...)andCOUNT(DISTINCT ...). InCOUNT(DISTINCT CASE WHEN safety_flag = FALSE THEN user_id END), safe rows evaluate toNULL(because there is noELSEclause), and SQL'sCOUNTskipsNULLautomatically — counting only distinct users who had at least one unsafe engagement that day!-- Compute unsafe and total counts in one pass without a WHERE filter so totals stay intact. SELECT DATE(created_at) AS day, SUM(CASE WHEN safety_flag = FALSE THEN 1 ELSE 0 END) AS unsafe_conversation_engagements, -- Safe rows become NULL here, and COUNT(DISTINCT ...) ignores NULLs. COUNT(DISTINCT CASE WHEN safety_flag = FALSE THEN user_id END) AS unsafe_users, COUNT(*) AS total_engagements, COUNT(DISTINCT user_id) AS total_users, 1.0 * SUM(CASE WHEN safety_flag = FALSE THEN 1 ELSE 0 END) / COUNT(*) AS unsafe_engagement_ratio, 1.0 * COUNT(DISTINCT CASE WHEN safety_flag = FALSE THEN user_id END) / COUNT(DISTINCT user_id) AS unsafe_user_ratio FROM conversations GROUP BY DATE(created_at) ORDER BY day ASC;In Python, each day maintains two integer counters plus two
sets ofuser_ids (usersandunsafe_users):from typing import Any, Dict, List def daily_unsafe_user_metrics(conversations: List[Dict]) -> List[Dict]: # stats_by_day[day] = {"engagements": int, "unsafe_engagements": int, "users": set, "unsafe_users": set} stats_by_day: Dict[str, Dict[str, Any]] = {} for conversation in conversations: day = utc_day_of(conversation["created_at"]) if day not in stats_by_day: stats_by_day[day] = { "engagements": 0, "unsafe_engagements": 0, "users": set(), "unsafe_users": set(), } stats = stats_by_day[day] stats["engagements"] += 1 stats["users"].add(conversation["user_id"]) if is_unsafe(conversation["safety_flag"]): stats["unsafe_engagements"] += 1 stats["unsafe_users"].add(conversation["user_id"]) rows = [] for day in sorted(stats_by_day): stats = stats_by_day[day] rows.append({ "day": day, "unsafe_conversation_engagements": stats["unsafe_engagements"], "unsafe_users": len(stats["unsafe_users"]), "total_engagements": stats["engagements"], "total_users": len(stats["users"]), "unsafe_engagement_ratio": stats["unsafe_engagements"] / stats["engagements"], "unsafe_user_ratio": len(stats["unsafe_users"]) / len(stats["users"]), }) return rowsTrace Example 1 across all five outputs
Let's verify Example 1 by hand:
Inputs: characters: #10 (2025-04-10, True), #20 (2025-04-10, False), #30 (2025-04-11, False), #40 (2025-04-13, False) conversations: 2025-04-13: conv 901 (char #10, user 501, True), conv 902 (char #20, user 502, False) 2025-04-14: conv 903 (char #10, user 501, True), conv 903 (char #10, user 503, False), conv 904 (char #20, user 503, True), conv 905 (char #30, user 502, False) Results: - top_characters: #10 -> 3, #20 -> 2, #30 -> 1, #40 -> 0 - unsafe_character_ratio: 3 unsafe out of 4 characters = 0.75 - daily_unsafe_character_pct: 2025-04-10 -> 1/2 = 0.5, ma7 = 0.5 2025-04-11 -> 1/1 = 1.0, ma7 = (0.5 + 1.0) / 2 = 0.75 2025-04-13 -> 1/1 = 1.0, ma7 = (0.5 + 1.0 + 1.0) / 3 = 5/6 - safety_breakdown: (False, False)=2 [902, 905], (False, True)=1 [904], (True, False)=1 [903/503], (True, True)=2 [901, 903/501] - daily_unsafe_user_metrics: 2025-04-13 -> unsafe_eng=1, unsafe_users=1 ({502}), total_eng=2, total_users=2 -> 0.5, 0.5 2025-04-14 -> unsafe_eng=2, unsafe_users=2 ({502,503}), total_eng=4, total_users=3 -> 0.5, 2/3Complete solution
from typing import Any, Dict, List, Optional, Set, Tuple from datetime import date, timedelta def is_unsafe(flag: Optional[bool]) -> bool: """Mirror SQL `safety_flag = FALSE`: False is unsafe; True and None (NULL) are not.""" # Checking `flag is not None` first prevents `not None` (which is True in Python!) # from misclassifying missing NULL flags as unsafe. return flag is not None and not flag def utc_day_of(timestamp: str) -> str: """Extract the 'YYYY-MM-DD' UTC calendar date from an ISO timestamp string.""" # Both '2025-04-10T09:00:00Z' and '2025-08-01 09:00:00' begin with 'YYYY-MM-DD'. return timestamp[:10] def top_characters( characters: List[Dict], conversations: List[Dict], limit: int = 100 ) -> List[Dict]: # engagement_count: dict[character_id, int] seeded at 0 for every character (SQL LEFT JOIN) engagement_count: Dict[Any, int] = {} for character in characters: engagement_count[character["character_id"]] = 0 for conversation in conversations: character_id = conversation["character_id"] if character_id in engagement_count: engagement_count[character_id] += 1 # Sort by (-count, character_id) so highest counts come first and ties break deterministically. ranked = [] for character_id, count in engagement_count.items(): ranked.append((-count, character_id)) ranked.sort() rows = [] for negative_count, character_id in ranked[:limit]: rows.append({"character_id": character_id, "engagement_count": -negative_count}) return rows def unsafe_character_ratio(characters: List[Dict]) -> float: if not characters: return 0.0 unsafe_count = 0 for character in characters: if is_unsafe(character["safety_flag"]): unsafe_count += 1 return unsafe_count / len(characters) def daily_unsafe_character_pct(characters: List[Dict]) -> List[Dict]: # Phase 1: Aggregate total and unsafe created characters per UTC day. total_by_day: Dict[str, int] = {} unsafe_by_day: Dict[str, int] = {} for character in characters: day = utc_day_of(character["created_at"]) total_by_day[day] = total_by_day.get(day, 0) + 1 if is_unsafe(character["safety_flag"]): unsafe_by_day[day] = unsafe_by_day.get(day, 0) + 1 # ISO 'YYYY-MM-DD' strings sort in exact chronological order. days = sorted(total_by_day) pct_by_day: Dict[str, float] = {} for day in days: pct_by_day[day] = unsafe_by_day.get(day, 0) / total_by_day[day] # Phase 2: For each active day, average daily_unsafe_pct across active days in [day - 6, day]. rows = [] for i, day in enumerate(days): window_start = (date.fromisoformat(day) - timedelta(days=6)).isoformat() # Because `days` has unique dates, walking backward inside a 7-day span takes <= 7 steps. window_sum = 0.0 window_days = 0 j = i while j >= 0 and days[j] >= window_start: window_sum += pct_by_day[days[j]] window_days += 1 j -= 1 rows.append({ "day": day, "daily_unsafe_pct": pct_by_day[day], "daily_unsafe_pct_ma7": window_sum / window_days, }) return rows def safety_breakdown(characters: List[Dict], conversations: List[Dict]) -> List[Dict]: # flag_by_character: dict[character_id, Optional[bool]] for O(1) inner-join lookup flag_by_character: Dict[Any, Optional[bool]] = {} for character in characters: flag_by_character[character["character_id"]] = character["safety_flag"] # Seed all four (character_flag, conversation_flag) combinations at 0 so empty cells stay visible. cells = [(False, False), (False, True), (True, False), (True, True)] count_by_cell = {cell: 0 for cell in cells} for conversation in conversations: character_id = conversation["character_id"] if character_id not in flag_by_character: continue cell = (flag_by_character[character_id], conversation["safety_flag"]) # A None flag on either side matches none of the four boolean cells, mirroring SQL JOIN. if cell in count_by_cell: count_by_cell[cell] += 1 rows = [] for character_flag, conversation_flag in cells: rows.append({ "character_safety_flag": character_flag, "conversation_safety_flag": conversation_flag, "engagement_count": count_by_cell[(character_flag, conversation_flag)], }) return rows def daily_unsafe_user_metrics(conversations: List[Dict]) -> List[Dict]: # stats_by_day[day] = {"engagements": int, "unsafe_engagements": int, "users": set, "unsafe_users": set} stats_by_day: Dict[str, Dict[str, Any]] = {} for conversation in conversations: day = utc_day_of(conversation["created_at"]) if day not in stats_by_day: stats_by_day[day] = { "engagements": 0, "unsafe_engagements": 0, "users": set(), "unsafe_users": set(), } stats = stats_by_day[day] stats["engagements"] += 1 stats["users"].add(conversation["user_id"]) if is_unsafe(conversation["safety_flag"]): stats["unsafe_engagements"] += 1 stats["unsafe_users"].add(conversation["user_id"]) rows = [] for day in sorted(stats_by_day): stats = stats_by_day[day] rows.append({ "day": day, "unsafe_conversation_engagements": stats["unsafe_engagements"], "unsafe_users": len(stats["unsafe_users"]), "total_engagements": stats["engagements"], "total_users": len(stats["users"]), "unsafe_engagement_ratio": stats["unsafe_engagements"] / stats["engagements"], "unsafe_user_ratio": len(stats["unsafe_users"]) / len(stats["users"]), }) return rows def compute_character_safety_engagement_metrics( users: List[Dict], characters: List[Dict], conversations: List[Dict] ) -> Dict: # Every required metric derives directly from `characters` and `conversations`. return { "top_characters": top_characters(characters, conversations), "unsafe_character_ratio": unsafe_character_ratio(characters), "daily_unsafe_character_pct": daily_unsafe_character_pct(characters), "safety_breakdown": safety_breakdown(characters, conversations), "daily_unsafe_user_metrics": daily_unsafe_user_metrics(conversations), }✅ Submit now — all tests should pass.
Intuition & how it works
Think of platform safety analytics like auditing both a library's book catalog (characters) and its daily checkout log (conversations): catalog metrics measure how many unsafe items are being created overall and day-by-day, while checkout metrics join sessions back to the catalog to see whether unsafe sessions come mainly from unsafe personas or also happen on safe ones. Every one of the five outputs follows the same clean recipe: pre-seed any required zero-count buckets (LEFT JOIN / CROSS JOIN), group rows in a single pass using conditional aggregation (putting CASE WHEN ... END inside SUM, AVG, or COUNT so safe and unsafe rows are tallied side by side without filtering rows out), and apply calendar-aware date windows.
Why do obvious SQL queries go wrong here? Using an inner join for top characters or a bare GROUP BY for the 2 x 2 breakdown silently drops personas with 0 engagements and empty cells of the matrix, while adding WHERE safety_flag = FALSE to the daily user query erases the safe rows needed for total_engagements and total_users. Most subtly, computing the 7-day moving average with ROWS BETWEEN 6 PRECEDING AND CURRENT ROW averages the last 7 rows instead of the last 7 calendar days, silently stretching across quiet periods whenever intermediate dates have no newly created personas.
Let's trace the 7-day moving average across Example 1 (2025-04-12 has no created personas) and Example 2 (2025-08-01 vs 2025-08-10):
Example 1:
Day Unsafe / Total daily_unsafe_pct Calendar window [day - 6, day] ma7
---------- -------------- ---------------- ----------------------------------------- ------
2025-04-10 1 / 2 0.5000 {Apr 10} -> 0.5 / 1 0.5000
2025-04-11 1 / 1 1.0000 {Apr 10, Apr 11} -> (0.5 + 1.0) / 2 0.7500
(2025-04-12 has no rows, so no output row is emitted, and the denominator on Apr 13 is 3)
2025-04-13 1 / 1 1.0000 {Apr 10, Apr 11, Apr 13} -> 2.5 / 3 0.8333
Example 2:
2025-08-01 1 / 1 1.0000 {Aug 01} -> 1.0 / 1 1.0000
2025-08-10 0 / 1 0.0000 [Aug 04..Aug 10] has only {Aug 10} 0.0000
Complexity
Let C be the number of rows in characters, V be the number of rows in conversations, D <= C be the number of distinct character-creation days, and E <= V be the number of distinct conversation days.
- Time:
O(C log C + V + E log E)average time in Python. Each helper scanscharacters(O(C)) and/orconversations(O(V)) once usingO(1)average-time dictionary and set lookups. Sorting character ranks takesO(C log C), sortingDandEdistinct date strings takesO(D log D + E log E), and the backward calendar scan inspects at most7distinct dates per day (O(D)). In SQL, all five queries execute as linearO(C + V)hash-join / hash-aggregate scans;ORDER BY ... LIMIT 100uses a bounded top-100 heap (O(C log 100)), and the moving-average self-join operates on the compactD-row daily summary rather than raw rows. An index onconversations(character_id)accelerates the top-100 join, and indexes oncharacters(created_at)andconversations(created_at)speed up date-range filtering. - Space:
O(C + V). We keep per-character dictionaries of sizeO(C), per-day summaries of sizeO(D + E), and per-dayuser_idsets whose combined cardinality across all days is at mostV.
Edge cases
- Characters with zero engagements: Kept in
top_characterswithengagement_count = 0viaLEFT JOIN+COUNT(cv.character_id)(Example 1, character40). - Ties at rank 100 and fewer than 100 characters: Breaking ties by
character_id ASCmakes the 100-row cutoff deterministic; whenC < 100, allCcharacters are returned. - Missing calendar days and month/leap-year boundaries: Days with zero created characters emit no row in
daily_unsafe_character_pct, anddate.fromisoformat(day) - timedelta(days=6)(or SQLDATE(d.day, '-6 days')) handles month lengths and leap days (2024-02-29) accurately. - Multiple users in one
conversation_id: Every row inconversationscounts as a separate engagement (Example 1,conversation_id = 903), whileunsafe_usersandtotal_usersdeduplicateuser_idper day. - Empty tables: Python returns
0.0forunsafe_character_ratio,[]for the daily/top lists, and0in all four cells ofsafety_breakdown(in SQL, wrapAVG(...)withCOALESCE(..., 0.0)if0.0is preferred overNULLon an empty table). NULL(None) safety flags: Mirrors SQLsafety_flag = FALSE:Noneis not counted as unsafe, stays in overall/daily denominators, and matches none of the four boolean(False/True, False/True)cells insafety_breakdown.
Common mistakes
- Writing
COUNT(*)afterLEFT JOINintop_characters: Turns zero-conversation characters intoengagement_count = 1becauseCOUNT(*)counts theNULL-padded row. Always count a non-null right-table column (COUNT(cv.character_id)). - Integer division in SQL (
SUM(...) / COUNT(*)): In SQLite, PostgreSQL, and SQL Server, dividing two integers truncates2 / 3to0. Multiply by1.0or average1.0/0.0. - Using
ROWS BETWEEN 6 PRECEDING AND CURRENT ROWfor the 7-day moving average: Counts 7 table rows instead of 7 calendar days, pulling stale dates (such as2025-08-01into2025-08-10in Example 2) into the window whenever quiet days occur. - Pooling counts across 7 days instead of averaging daily rates: Dividing 7-day unsafe characters by 7-day total characters gives
3 / 4 = 0.75on2025-04-13in Example 1 instead of the specified(0.5 + 1.0 + 1.0) / 3 = 5/6. - Filtering
WHERE safety_flag = FALSEindaily_unsafe_user_metrics(or plainGROUP BYinsafety_breakdown): Drops safe rows needed fortotal_engagements/total_users, and drops0-count cells in the2 x 2table. - Writing
not flagin Python withoutflag is not None: In Pythonnot NoneisTrue, which falsely marks missing flags as unsafe.
Alternative approaches
- Calendar-range window function: A window function (a SQL
OVER (...)clause that computes an aggregate across a sliding frame of neighboring rows without collapsing them) can replace the self-join when usingRANGEover calendar dates. PostgreSQL 11+ supportsAVG(daily_unsafe_pct) OVER (ORDER BY day RANGE BETWEEN INTERVAL '6 days' PRECEDING AND CURRENT ROW)directly, and SQLite 3.28+ supports the same idea by converting dates to numeric Julian days (ORDER BY JULIANDAY(day) RANGE BETWEEN 6 PRECEDING AND CURRENT ROW). - Calendar spine (
date_spineCTE): If a product dashboard wants missing dates to appear explicitly as0rather than skipping quiet days, generate every calendar date in the range with a recursive CTE andLEFT JOINthe daily aggregates onto it.
Follow-up questions
- How would you adjust the top-100 ranking query so that every character tied at the 100th rank is retained instead of truncated? Replace
ORDER BY ... LIMIT 100with a CTE that computesRANK() OVER (ORDER BY engagement_count DESC) AS rnkand filtersWHERE rnk <= 100. BecauseRANK()assigns identical ranks to equal counts (for example, three personas tied at 99th all receivernk = 99and the next receives102), every persona tied at the cutoff stays in the result instead of being arbitrarily dropped at row 100. - When should a dashboard report a volume-weighted 7-day unsafe rate instead of averaging the daily unsafe percentages equally? An unweighted mean gives equal weight to a quiet holiday with
2new personas and a major launch day with20,000new personas, making the line volatile on low-volume days. A volume-weighted (pooled) rate —SUM(daily_unsafe_count) * 1.0 / SUM(daily_total_count)over[day - 6, day]— weights every created persona equally to reflect overall catalog risk, whereas the unweighted daily mean is preferable when auditing day-to-day moderation stability independent of traffic spikes. - What statistical pitfalls arise if you run a standard chi-square test directly on the 2x2 engagement table? A naive chi-square test treats every engagement row in
conversationsas an independent observation, which fails badly when one popular persona or heavy user accounts for thousands of correlated rows and artificially inflates statistical significance. Instead, compare conditional unsafe ratesP(unsafe conv | unsafe char)vsP(unsafe conv | safe char)using cluster-robust standard errors (clustered oncharacter_idanduser_id) or stratify by persona traffic tier before drawing conclusions.
Follow-up questions
- How would you adjust the top-100 ranking query so that every character tied at the 100th rank is retained instead of truncated?
- When should a dashboard report a volume-weighted 7-day unsafe rate instead of averaging the daily unsafe percentages equally?
- What statistical pitfalls arise if you run a standard chi-square test directly on the 2x2 engagement table?
Similar questions
- Shortest Covering Substring
- Job Posting Engagement Metrics Excluding Non-Viewing Applicants
- Compute 7-Day DAU, D1 Retention, and Revenue Cohorts
- Class-Level 2024 Exam Summary with Zero-Filled Averages
- Summarizing Imaging Claims Spend and Fiscal Months
- Build Rolling User Features for Experiment Regression
More Character.AI interview questions
- Shortest Covering Substring Medium