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

  1. users
    • user_id (int / BIGINT): unique account identifier.
    • created_at (str / TIMESTAMP): UTC account creation timestamp.
  2. characters
    • character_id (int / BIGINT): unique persona identifier.
    • created_by_user_id (int / BIGINT): creator's user_id.
    • created_at (str / TIMESTAMP): UTC persona creation timestamp.
    • safety_flag (Optional[bool] / BOOLEAN): persona moderation status.
  3. conversations
    • conversation_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:

  1. "top_characters" — Up to 100 personas ranked by total matching rows in conversations across all time (engagement_count descending, breaking ties by character_id ascending). Personas with zero engagements must still be eligible with engagement_count = 0. Each list element is {"character_id": int, "engagement_count": int}.
  2. "unsafe_character_ratio" — A float in [0.0, 1.0] giving the share of rows in characters where safety_flag is False (return 0.0 when characters is empty).
  3. "daily_unsafe_character_pct" — One summary row per UTC day on which at least one persona was created, sorted by day ascending. Each element is {"day": str, "daily_unsafe_pct": float, "daily_unsafe_pct_ma7": float}, where:
    • daily_unsafe_pct is (# unsafe personas created on day) / (total personas created on day).
    • daily_unsafe_pct_ma7 is the unweighted mean of daily_unsafe_pct over 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).
  4. "safety_breakdown" — A 4-row 2 x 2 contingency table joining conversations to characters on character_id and 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) with engagement_count = 0 when a pair has no matches: {"character_safety_flag": bool, "conversation_safety_flag": bool, "engagement_count": int}.
  5. "daily_unsafe_user_metrics" — One row per UTC day present in conversations, sorted by day ascending, containing:
    • "day": YYYY-MM-DD string,
    • "unsafe_conversation_engagements": rows that day with safety_flag == False,
    • "unsafe_users": distinct user_id values with at least one safety_flag == False row that day,
    • "total_engagements": all conversation rows that day,
    • "total_users": distinct user_id values 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_at string starts with an ISO UTC calendar date YYYY-MM-DD (YYYY-MM-DDTHH:MM:SSZ or YYYY-MM-DD HH:MM:SS).
  • character_id values in characters are unique.
  • safety_flag is True, False, or None; only False counts as unsafe.
  • Days with zero created characters do not appear in daily_unsafe_character_pct, and days with zero conversations do not appear in daily_unsafe_user_metrics.

Step-by-step walkthrough

  1. Understand the schema, return shape, and metric rules

    We have three product tables (users, characters, conversations) where safety_flag = TRUE means safe and safety_flag = FALSE means 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 function compute_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 40 with engagement_count: 0, so we must start from characters (LEFT JOIN), not conversations. 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 counts 3/4 = 0.75). 3. View 4 always outputs all four (False/True, False/True) rows: Even when a cell has 0 conversations (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 FALSE checks 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]
    
  2. View 1: Top 100 characters by conversation engagements

    Each row in conversations counts as one engagement (even if multiple users share the same conversation_id). To keep characters with zero engagements, we use a LEFT JOIN (a join that keeps every row from the left table characters and fills unmatched columns from conversations with NULL).

    Pay close attention to COUNT(cv.character_id) vs COUNT(*): for a character with zero conversations, LEFT JOIN still produces one row with cv.character_id = NULL. COUNT(*) would count that row as 1, whereas COUNT(cv.character_id) ignores NULLs and rightly returns 0!

    -- 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, add 1 per 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 rows
    
  3. View 2: Overall unsafe character ratio

    The fraction of rows satisfying a condition equals the average of a 1.0 / 0.0 indicator column. Using conditional aggregation (placing CASE WHEN ... END inside AVG) computes the ratio in one pass, and writing floating-point 1.0 and 0.0 avoids 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 characters list (returning 0.0) and divide unsafe characters by len(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)
    
  4. View 3: 7-day calendar moving average of daily unsafe percentage

    First, group characters by DATE(created_at) inside a CTE (Common Table Expression — a named temporary table defined with WITH so later steps can query it cleanly). Next, for each day d, average daily_unsafe_pct over 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-12 missing) and Example 2 (2025-08-01 vs 2025-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 d to daily AS w on w.day BETWEEN DATE(d.day, '-6 days') AND d.day obeys true calendar dates in SQLite (and in PostgreSQL with d.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 day days[i] we walk backward (j = i, i - 1, ...) while days[j] >= (date - 6 days). Since dates in days are 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 rows
    
  5. View 4: Complete 2x2 character-vs-conversation safety breakdown

    We want all four cells of the 2x2 table comparing characters.safety_flag against conversations.safety_flag:

                           conversation_safety_flag
                            FALSE            TRUE
    character  FALSE   (False, False)   (False, True)
    safety     TRUE    (True,  False)   (True,  True)
    

    A plain GROUP BY omits any cell that happens to have zero matching conversations. To guarantee all 4 rows appear with 0 when empty, we build the 4 boolean pairs with a CROSS JOIN and LEFT JOIN the 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_cell with all four (False/True, False/True) tuples set to 0 and look up each conversation's character in O(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 rows
    
  6. View 5: Daily unsafe engagements and distinct unsafe users

    View 5 needs both unsafe counts and all-conversation totals per day from conversations. Do not write WHERE safety_flag = FALSE — that would filter out safe conversations and ruin total_engagements and total_users!

    Instead, use conditional aggregation inside SUM(...) and COUNT(DISTINCT ...). In COUNT(DISTINCT CASE WHEN safety_flag = FALSE THEN user_id END), safe rows evaluate to NULL (because there is no ELSE clause), and SQL's COUNT skips NULL automatically — 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 of user_ids (users and unsafe_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 rows
    
  7. Trace 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/3
    
  8. Complete 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 scans characters (O(C)) and/or conversations (O(V)) once using O(1) average-time dictionary and set lookups. Sorting character ranks takes O(C log C), sorting D and E distinct date strings takes O(D log D + E log E), and the backward calendar scan inspects at most 7 distinct dates per day (O(D)). In SQL, all five queries execute as linear O(C + V) hash-join / hash-aggregate scans; ORDER BY ... LIMIT 100 uses a bounded top-100 heap (O(C log 100)), and the moving-average self-join operates on the compact D-row daily summary rather than raw rows. An index on conversations(character_id) accelerates the top-100 join, and indexes on characters(created_at) and conversations(created_at) speed up date-range filtering.
  • Space: O(C + V). We keep per-character dictionaries of size O(C), per-day summaries of size O(D + E), and per-day user_id sets whose combined cardinality across all days is at most V.

Edge cases

  • Characters with zero engagements: Kept in top_characters with engagement_count = 0 via LEFT JOIN + COUNT(cv.character_id) (Example 1, character 40).
  • Ties at rank 100 and fewer than 100 characters: Breaking ties by character_id ASC makes the 100-row cutoff deterministic; when C < 100, all C characters are returned.
  • Missing calendar days and month/leap-year boundaries: Days with zero created characters emit no row in daily_unsafe_character_pct, and date.fromisoformat(day) - timedelta(days=6) (or SQL DATE(d.day, '-6 days')) handles month lengths and leap days (2024-02-29) accurately.
  • Multiple users in one conversation_id: Every row in conversations counts as a separate engagement (Example 1, conversation_id = 903), while unsafe_users and total_users deduplicate user_id per day.
  • Empty tables: Python returns 0.0 for unsafe_character_ratio, [] for the daily/top lists, and 0 in all four cells of safety_breakdown (in SQL, wrap AVG(...) with COALESCE(..., 0.0) if 0.0 is preferred over NULL on an empty table).
  • NULL (None) safety flags: Mirrors SQL safety_flag = FALSE: None is not counted as unsafe, stays in overall/daily denominators, and matches none of the four boolean (False/True, False/True) cells in safety_breakdown.

Common mistakes

  • Writing COUNT(*) after LEFT JOIN in top_characters: Turns zero-conversation characters into engagement_count = 1 because COUNT(*) counts the NULL-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 truncates 2 / 3 to 0. Multiply by 1.0 or average 1.0 / 0.0.
  • Using ROWS BETWEEN 6 PRECEDING AND CURRENT ROW for the 7-day moving average: Counts 7 table rows instead of 7 calendar days, pulling stale dates (such as 2025-08-01 into 2025-08-10 in 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.75 on 2025-04-13 in Example 1 instead of the specified (0.5 + 1.0 + 1.0) / 3 = 5/6.
  • Filtering WHERE safety_flag = FALSE in daily_unsafe_user_metrics (or plain GROUP BY in safety_breakdown): Drops safe rows needed for total_engagements/total_users, and drops 0-count cells in the 2 x 2 table.
  • Writing not flag in Python without flag is not None: In Python not None is True, 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 using RANGE over calendar dates. PostgreSQL 11+ supports AVG(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_spine CTE): If a product dashboard wants missing dates to appear explicitly as 0 rather than skipping quiet days, generate every calendar date in the range with a recursive CTE and LEFT JOIN the 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 100 with a CTE that computes RANK() OVER (ORDER BY engagement_count DESC) AS rnk and filters WHERE rnk <= 100. Because RANK() assigns identical ranks to equal counts (for example, three personas tied at 99th all receive rnk = 99 and the next receives 102), 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 2 new personas and a major launch day with 20,000 new 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 conversations as 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 rates P(unsafe conv | unsafe char) vs P(unsafe conv | safe char) using cluster-robust standard errors (clustered on character_id and user_id) or stratify by persona traffic tier before drawing conclusions.

Follow-up questions

Similar questions

More Character.AI interview questions

All 2 Character.AI questions →