Multi-Metric Live Broadcast Telemetry in SQL and Python

Medium · Data Manipulation (SQL/Python) · Data Scientist · Technical Screen

Problem Statement

You are analyzing minute-by-minute telemetry from a live video platform stored across two tables of different granularities:

  • minute_streamed (one row per live broadcast minute of a creator):
    • time_minute (TIMESTAMP / UTC string "YYYY-MM-DDTHH:MM:SS" or "YYYY-MM-DD HH:MM:SS")
    • streamer_username (VARCHAR / str)
    • category (VARCHAR / Optional[str]; creators can switch categories between any two minutes, and category may be None)
    • concurrent_viewers (INTEGER / int)
  • minute_viewed (one row per audience member watching one creator for one minute):
    • time_minute (TIMESTAMP / UTC string)
    • viewer_username (VARCHAR / str)
    • viewer_country (VARCHAR / str, such as "US", "CA", "GB")
    • streamer_username (VARCHAR / str)

Each row in minute_streamed represents 1 broadcast minute (1 / 60.0 of an hour), and calendar months are UTC "YYYY-MM" buckets derived from time_minute.

Implement streaming_analytics(minute_streamed: List[Dict], minute_viewed: List[Dict], cat_keyword: str) -> Dict returning a dictionary with four keys:

  1. "monthly_hours": Total broadcast hours (minutes / 60.0) summed across all creators for each active calendar month "YYYY-MM". Return [month_yyyy_mm, hours_streamed] rows ordered chronologically by month_yyyy_mm.
  2. "streamer_category_totals": For each creator in minute_streamed, return [streamer_username, total_minutes, keyword_minutes, keyword_share] sorted ascending by streamer_username, where keyword_minutes counts broadcast minutes whose non-null category contains cat_keyword (case-insensitive substring match) and keyword_share = keyword_minutes / total_minutes.
  3. "monthly_increases": For each creator and active month "YYYY-MM", compare their streamed minutes current_minutes against prev_minutes in the immediately preceding calendar month (treating an unstreamed prior calendar month as 0 minutes, and rolling "YYYY-01" back to "(YYYY-1)-12"). Return [streamer_username, month_yyyy_mm, current_minutes, prev_minutes] only where current_minutes > prev_minutes, sorted ascending by (streamer_username, month_yyyy_mm).
  4. "year_2019": Restricted to calendar year 2019, for every creator with at least one 2019 row in minute_streamed, return [streamer_username, avg_concurrent_viewers_2019, us_viewer_minutes_2019, unique_streaming_minutes_with_us_2019] sorted ascending by streamer_username:
    • avg_concurrent_viewers_2019: mean of concurrent_viewers across that creator's 2019 rows in minute_streamed alone (not weighted by viewer rows), rounded to 4 decimal places.
    • us_viewer_minutes_2019: total 2019 rows in minute_viewed with viewer_country == "US" whose (streamer_username, time_minute) matches a 2019 row in minute_streamed (0 if none).
    • unique_streaming_minutes_with_us_2019: number of distinct 2019 broadcast minutes for that creator in minute_streamed with at least one matching "US" viewer row (0 if none).

Examples

Example 1

Input:
minute_streamed = [
  {"time_minute": "2018-12-31T23:58:00", "streamer_username": "nova",  "category": "ActionRPG", "concurrent_viewers": 80},
  {"time_minute": "2019-01-01T00:00:00", "streamer_username": "nova",  "category": "ActionRPG", "concurrent_viewers": 90},
  {"time_minute": "2019-01-01T00:01:00", "streamer_username": "nova",  "category": "rpg_maker", "concurrent_viewers": 110},
  {"time_minute": "2019-04-10T18:00:00", "streamer_username": "pixel", "category": "Chess",     "concurrent_viewers": 30},
  {"time_minute": "2019-04-10T18:01:00", "streamer_username": "pixel", "category": "RetroRPG",  "concurrent_viewers": 40},
  {"time_minute": "2019-04-10T18:02:00", "streamer_username": "pixel", "category": "Chess",     "concurrent_viewers": 50},
  {"time_minute": "2020-02-05T12:00:00", "streamer_username": "nova",  "category": "Music",     "concurrent_viewers": 75}
]
minute_viewed = [
  {"time_minute": "2019-01-01T00:00:00", "viewer_username": "v_amy", "viewer_country": "US", "streamer_username": "nova"},
  {"time_minute": "2019-01-01T00:00:00", "viewer_username": "v_ben", "viewer_country": "US", "streamer_username": "nova"},
  {"time_minute": "2019-01-01T00:01:00", "viewer_username": "v_amy", "viewer_country": "US", "streamer_username": "nova"},
  {"time_minute": "2019-04-10T18:00:00", "viewer_username": "v_kai", "viewer_country": "CA", "streamer_username": "pixel"},
  {"time_minute": "2019-04-10T18:01:00", "viewer_username": "v_leo", "viewer_country": "US", "streamer_username": "pixel"},
  {"time_minute": "2020-02-05T12:00:00", "viewer_username": "v_amy", "viewer_country": "US", "streamer_username": "nova"}
]
cat_keyword = "rpg"

Output:
{
  "monthly_hours": [
    ["2018-12", 0.016666666666666666],
    ["2019-01", 0.03333333333333333],
    ["2019-04", 0.05],
    ["2020-02", 0.016666666666666666]
  ],
  "streamer_category_totals": [
    ["nova", 4, 3, 0.75],
    ["pixel", 3, 1, 0.3333333333333333]
  ],
  "monthly_increases": [
    ["nova", "2018-12", 1, 0],
    ["nova", "2019-01", 2, 1],
    ["nova", "2020-02", 1, 0],
    ["pixel", "2019-04", 3, 0]
  ],
  "year_2019": [
    ["nova", 100.0, 3, 2],
    ["pixel", 40.0, 1, 1]
  ]
}

Walk-through: - "nova" matches "rpg" in 3 of 4 total minutes ("ActionRPG", "ActionRPG", "rpg_maker" -> 0.75), while "pixel" matches in 1 of 3 ("RetroRPG" -> 1/3). - In "2020-02", "nova" streamed 1 minute after 0 minutes in "2020-01", so "2020-02" counts as an increase (1 > 0) even though "nova" streamed 2 minutes back in "2019-01". - In 2019, "nova" averaged (90 + 110) / 2 = 100.0 concurrent viewers and logged 3 US viewer-minutes across 2 distinct broadcast minutes (00:00 had two US viewers; 00:01 had one).

Example 2

Input:
minute_streamed = [
  {"time_minute": "2019-05-20T10:00:00", "streamer_username": "sol", "category": "Jazz",   "concurrent_viewers": 10},
  {"time_minute": "2019-05-20T10:01:00", "streamer_username": "sol", "category": "Jazz",   "concurrent_viewers": 15},
  {"time_minute": "2019-06-01T10:00:00", "streamer_username": "sol", "category": "Coding", "concurrent_viewers": 14}
]
minute_viewed = [
  {"time_minute": "2019-05-20T10:00:00", "viewer_username": "v_uk", "viewer_country": "GB", "streamer_username": "sol"}
]
cat_keyword = "JAZZ"

Output:
{
  "monthly_hours": [
    ["2019-05", 0.03333333333333333],
    ["2019-06", 0.016666666666666666]
  ],
  "streamer_category_totals": [
    ["sol", 3, 2, 0.6666666666666666]
  ],
  "monthly_increases": [
    ["sol", "2019-05", 2, 0]
  ],
  "year_2019": [
    ["sol", 13.0, 0, 0]
  ]
}

Walk-through: "sol" drops from 2 minutes in "2019-05" to 1 minute in "2019-06", so "2019-06" is omitted from "monthly_increases". In 2019, "sol" averages (10 + 15 + 14) / 3 = 13.0 viewers and still appears in "year_2019" with 0 US viewer-minutes because the sole viewer was from "GB".

Constraints

  • 0 <= len(minute_streamed), len(minute_viewed) <= 10^5
  • time_minute is a valid UTC timestamp string ("YYYY-MM-DDTHH:MM:SS" or "YYYY-MM-DD HH:MM:SS")
  • 0 <= concurrent_viewers <= 10^7
  • category is str or None; 0 <= len(cat_keyword) <= 100

Step-by-step walkthrough

  1. Understand the two event grains and output contract

    We have two minute-level telemetry tables at different grains (levels of detail per row):

    • minute_streamed: one row per broadcast minute of a live streamer (time_minute, streamer_username, category, concurrent_viewers).
    • minute_viewed: one row per viewer per minute (time_minute, viewer_username, viewer_country, streamer_username). If 5 viewers watch nova during the same minute, minute_streamed has 1 row while minute_viewed has 5 rows.

    For the automated Python judge, streaming_analytics(minute_streamed, minute_viewed, cat_keyword) receives both tables as lists of dictionaries plus cat_keyword, and returns one dictionary with four sorted result tables corresponding to Tasks 1–4:

    "monthly_hours":            [month_yyyy_mm, hours_streamed]                    sorted by month
    "streamer_category_totals": [streamer, total_mins, keyword_mins, share]        sorted by streamer
    "monthly_increases":        [streamer, month_yyyy_mm, current_mins, prev_mins] sorted by streamer, month
    "year_2019":                [streamer, avg_viewers_2019 (4 decimals),
                                 us_viewer_mins_2019, unique_us_mins_2019]         sorted by streamer
    

    Below we build the portable SQL query first for each of Tasks 1–4, followed immediately by the matching Python helper, and explain Task 5's SQL execution order.

  2. Task 1: bucket minutes by YYYY-MM so years stay separate

    Each row in minute_streamed equals 1 minute streamed, so hours equal COUNT(*) / 60.0 (using 60.0 instead of integer 60 prevents SQL integer division from truncating 2 / 60 to 0).

    Crucially, we must group by both year and month formatted as 'YYYY-MM'. Grouping by EXTRACT(MONTH FROM time_minute) alone would merge 2018-12 and 2019-12 into a single December bucket! Better yet, 'YYYY-MM' strings sort in exact chronological order when sorted alphabetically.

    -- Format timestamps as 'YYYY-MM' (PostgreSQL: TO_CHAR(time_minute, 'YYYY-MM'))
    SELECT strftime('%Y-%m', time_minute) AS month_yyyy_mm,
           COUNT(*) / 60.0 AS hours_streamed
    FROM minute_streamed
    GROUP BY strftime('%Y-%m', time_minute)
    ORDER BY month_yyyy_mm;
    

    In Python, we normalize timestamps ('T' vs ' ') into 'YYYY-MM-DD HH:MM:SS' and slice the first 7 characters:

    def normalize_timestamp(value: Any) -> str:
        """Normalize an ISO string (' ' or 'T') or datetime to 'YYYY-MM-DD HH:MM:SS'."""
        return str(value).replace("T", " ")[:19]
    
    
    def extract_year_month(value: Any) -> str:
        """Return 'YYYY-MM' so year boundaries stay distinct and text sort is chronological."""
        return normalize_timestamp(value)[:7]
    
    
    def compute_monthly_hours(minute_streamed: List[Dict]) -> List[List]:
        """Task 1: total streamed hours per active 'YYYY-MM' across all streamers."""
        # month_minutes: {'2018-12': 1, '2019-01': 2, ...}
        month_minutes: Dict[str, int] = {}
        for row in minute_streamed:
            month = extract_year_month(row["time_minute"])
            month_minutes[month] = month_minutes.get(month, 0) + 1
    
        # 'YYYY-MM' strings sort chronologically across year boundaries.
        result: List[List] = []
        for month in sorted(month_minutes):
            result.append([month, month_minutes[month] / 60])
        return result
    
  3. Task 2: compute case-insensitive category keyword share

    For each streamer, we want total_minutes, keyword_minutes (minutes whose category contains cat_keyword ignoring letter case), and keyword_share = keyword_minutes / total_minutes.

    In SQL, LIKE is case-sensitive in PostgreSQL and treats % and _ inside cat_keyword as wildcards. Lower-casing both strings and testing substring position with INSTR(LOWER(category), LOWER(:cat_keyword)) > 0 (PostgreSQL: POSITION(LOWER(:cat_keyword) IN LOWER(category)) > 0) handles mixed case portably, treats %/_ literally, and turns NULL categories safely into 0 via CASE.

    WITH flagged AS (
        -- Flag each streamed minute as 1 if category contains cat_keyword (case-insensitive), else 0
        SELECT streamer_username,
               CASE WHEN INSTR(LOWER(category), LOWER(:cat_keyword)) > 0
                    THEN 1 ELSE 0 END AS is_keyword
        FROM minute_streamed
    )
    SELECT streamer_username,
           COUNT(*) AS total_minutes,
           SUM(is_keyword) AS keyword_minutes,
           -- Multiply by 1.0 to force floating-point division
           1.0 * SUM(is_keyword) / COUNT(*) AS keyword_share
    FROM flagged
    GROUP BY streamer_username
    ORDER BY streamer_username;
    
    def compute_streamer_category_totals(minute_streamed: List[Dict], cat_keyword: str) -> List[List]:
        """Task 2: per-streamer total minutes, keyword-matched minutes, and share."""
        needle = cat_keyword.lower()
        # total_minutes / keyword_minutes: {'nova': 4, 'pixel': 3, ...}
        total_minutes: Dict[str, int] = {}
        keyword_minutes: Dict[str, int] = {}
    
        for row in minute_streamed:
            name = row["streamer_username"]
            if name not in total_minutes:
                total_minutes[name] = 0
                keyword_minutes[name] = 0
    
            total_minutes[name] += 1
            category = row["category"]
            # Guard against None categories and match case-insensitively on both sides.
            if category is not None and needle in category.lower():
                keyword_minutes[name] += 1
    
        result: List[List] = []
        for name in sorted(total_minutes):
            share = keyword_minutes[name] / total_minutes[name]
            result.append([name, total_minutes[name], keyword_minutes[name], share])
        return result
    
  4. Task 3: compare against the previous calendar month, not LAG

    Here is the #1 trap in monthly time-series SQL: LAG(minutes) OVER (PARTITION BY streamer_username ORDER BY month) fetches the previous row in the table (the previous active month), NOT the previous calendar month!

    Look at creator nova in Example 1:

    Calendar timeline for creator nova:
      2018-11   2018-12   2019-01   2019-02 ... 2020-01   2020-02
        0 min     1 min     2 min     0 min       0 min     1 min
    
    Naive LAG(minutes) at 2020-02 looks back to 2019-01 (2 min): 1 > 2 is False (WRONG!)
    Calendar rule      at 2020-02 looks back to 2020-01 (0 min): 1 > 0 is True  (CORRECT!)
    

    To compare against the true previous calendar month: 1. Aggregate active (streamer_username, month_start) rows using the first day of the month (DATE(time_minute, 'start of month') in SQLite; DATE_TRUNC('month', time_minute) in PostgreSQL). Always do month arithmetic on day 01 so 31-day months never overflow! 2. LEFT JOIN that monthly table (cur) to itself (prev) on the same streamer and prev.month_start = cur.month_start - 1 month. When the streamer did not stream in the previous calendar month, prev.minutes is NULL, which COALESCE(prev.minutes, 0) turns into 0. 3. Why don't we need rows where cur.minutes = 0? Because prev_minutes >= 0, so 0 > prev_minutes can never be true!

    WITH monthly AS (
        -- Normalize every timestamp to day 01 of its month before counting minutes
        SELECT streamer_username,
               DATE(time_minute, 'start of month') AS month_start,
               COUNT(*) AS minutes
        FROM minute_streamed
        GROUP BY streamer_username, DATE(time_minute, 'start of month')
    )
    SELECT cur.streamer_username,
           strftime('%Y-%m', cur.month_start) AS month_yyyy_mm,
           cur.minutes AS current_minutes,
           COALESCE(prev.minutes, 0) AS prev_minutes
    FROM monthly AS cur
    -- Self-LEFT JOIN to the exact preceding calendar month (NULL -> 0 when inactive)
    LEFT JOIN monthly AS prev
           ON prev.streamer_username = cur.streamer_username
          AND prev.month_start = DATE(cur.month_start, '-1 month')
    WHERE cur.minutes > COALESCE(prev.minutes, 0)
    ORDER BY cur.streamer_username, cur.month_start;
    
    def prev_calendar_month(month_yyyy_mm: str) -> str:
        """Return the 'YYYY-MM' label of the immediately preceding calendar month."""
        year = int(month_yyyy_mm[:4])
        month = int(month_yyyy_mm[5:7])
        # January rolls back to December of the previous year.
        if month == 1:
            return f"{year - 1:04d}-12"
        return f"{year:04d}-{month - 1:02d}"
    
    
    def compute_monthly_increases(minute_streamed: List[Dict]) -> List[List]:
        """Task 3: months where a streamer's minutes strictly beat the previous calendar month."""
        # streamer_month_minutes: {('nova', '2019-01'): 2, ...}
        streamer_month_minutes: Dict[Tuple[str, str], int] = {}
        for row in minute_streamed:
            key = (row["streamer_username"], extract_year_month(row["time_minute"]))
            streamer_month_minutes[key] = streamer_month_minutes.get(key, 0) + 1
    
        result: List[List] = []
        # Only active months can increase, because 0 > prev_minutes is impossible when prev >= 0.
        for streamer, month in sorted(streamer_month_minutes):
            current_mins = streamer_month_minutes[(streamer, month)]
            # Look up the previous calendar month (defaulting to 0 if inactive), NOT previous active month.
            prev_mins = streamer_month_minutes.get((streamer, prev_calendar_month(month)), 0)
            if current_mins > prev_mins:
                result.append([streamer, month, current_mins, prev_mins])
        return result
    
  5. Task 4: aggregate before joining to avoid viewer fan-out

    Why can't we simply LEFT JOIN minute_streamed TO minute_viewed and compute AVG(concurrent_viewers) and COUNT(US viewers) in one GROUP BY? Look at what happens to creator nova in 2019 when two viewers (v_amy and v_ben) watch the 00:00 minute:

    minute_streamed for nova:          After joining minute_viewed on (streamer, time_minute):
    00:00 | viewers =  90              00:00 | viewers =  90 | v_amy (US)  <-- 00:00 duplicated!
    00:01 | viewers = 110              00:00 | viewers =  90 | v_ben (US)  <-- 00:00 duplicated!
    True avg = (90+110)/2 = 100.0      00:01 | viewers = 110 | v_amy (US)
                                       Joined AVG = (90+90+110)/3 = 96.6667  (WRONG — fan-out!)
    

    This duplication is called join fan-out: joining a 1-row-per-minute table to a many-rows-per-minute table multiplies the broadcast rows! We prevent it cleanly with three steps: 1. avg_2019: compute AVG(concurrent_viewers) per streamer from minute_streamed alone in 2019. 2. us_2019: join minute_viewed (viewer_country = 'US') against SELECT DISTINCT streamer_username, time_minute FROM minute_streamed in 2019, counting COUNT(*) for total US viewer-minutes and COUNT(DISTINCT v.time_minute) for unique broadcast minutes with at least one US viewer. 3. LEFT JOIN us_2019 onto avg_2019 with COALESCE(..., 0) so 2019 streamers with zero US viewers still appear with 0, 0.

    WITH avg_2019 AS (
        -- 1. Average concurrent viewers at the broadcast-minute grain (no join fan-out)
        SELECT streamer_username,
               AVG(concurrent_viewers) AS avg_viewers
        FROM minute_streamed
        WHERE time_minute >= '2019-01-01' AND time_minute < '2020-01-01'
        GROUP BY streamer_username
    ),
    streamed_keys AS (
        -- 2. Distinct 2019 (streamer, minute) keys so duplicate stream rows cannot multiply viewers
        SELECT DISTINCT streamer_username, time_minute
        FROM minute_streamed
        WHERE time_minute >= '2019-01-01' AND time_minute < '2020-01-01'
    ),
    us_2019 AS (
        -- 3. Count matched US viewer-minutes and distinct minutes with >= 1 US viewer
        SELECT v.streamer_username,
               COUNT(*) AS us_viewer_minutes,
               COUNT(DISTINCT v.time_minute) AS us_minutes
        FROM minute_viewed AS v
        JOIN streamed_keys AS k
          ON k.streamer_username = v.streamer_username
         AND k.time_minute = v.time_minute
        WHERE v.viewer_country = 'US'
        GROUP BY v.streamer_username
    )
    SELECT a.streamer_username,
           ROUND(a.avg_viewers, 4) AS avg_concurrent_viewers_2019,
           COALESCE(u.us_viewer_minutes, 0) AS us_viewer_minutes_2019,
           COALESCE(u.us_minutes, 0) AS unique_streaming_minutes_with_us_2019
    FROM avg_2019 AS a
    -- LEFT JOIN preserves streamers who streamed in 2019 but had zero US viewers
    LEFT JOIN us_2019 AS u
           ON u.streamer_username = a.streamer_username
    ORDER BY a.streamer_username;
    
    def compute_year_2019_stats(minute_streamed: List[Dict], minute_viewed: List[Dict]) -> List[List]:
        """Task 4: 2019 avg concurrent viewers, US viewer-minutes, and distinct US minutes."""
        # Phase 1: aggregate 2019 broadcast stats from minute_streamed alone (prevents viewer fan-out).
        viewer_sum_2019: Dict[str, int] = {}
        stream_mins_2019: Dict[str, int] = {}
        # streamed_2019_keys: {('nova', '2019-01-01 00:00:00'), ...}
        streamed_2019_keys: Set[Tuple[str, str]] = set()
    
        for row in minute_streamed:
            moment = normalize_timestamp(row["time_minute"])
            if moment[:4] != "2019":
                continue
            name = row["streamer_username"]
            viewer_sum_2019[name] = viewer_sum_2019.get(name, 0) + row["concurrent_viewers"]
            stream_mins_2019[name] = stream_mins_2019.get(name, 0) + 1
            streamed_2019_keys.add((name, moment))
    
        # Phase 2: count US viewer-minutes that match a valid 2019 (streamer, minute) broadcast key.
        us_viewer_mins: Dict[str, int] = {}
        # us_distinct_moments: {'nova': {'2019-01-01 00:00:00', ...}}
        us_distinct_moments: Dict[str, Set[str]] = {}
    
        for row in minute_viewed:
            if row["viewer_country"] != "US":
                continue
            name = row["streamer_username"]
            moment = normalize_timestamp(row["time_minute"])
            # streamed_2019_keys contains only 2019 live minutes, filtering year and live match at once.
            if (name, moment) not in streamed_2019_keys:
                continue
            us_viewer_mins[name] = us_viewer_mins.get(name, 0) + 1
            if name not in us_distinct_moments:
                us_distinct_moments[name] = set()
            us_distinct_moments[name].add(moment)
    
        # Phase 3: left-join US stats onto every 2019 streamer so 0-US streamers stay included.
        result: List[List] = []
        for name in sorted(stream_mins_2019):
            avg_viewers = round(viewer_sum_2019[name] / stream_mins_2019[name], 4)
            total_us_rows = us_viewer_mins.get(name, 0)
            distinct_us_mins = len(us_distinct_moments.get(name, set()))
            result.append([name, avg_viewers, total_us_rows, distinct_us_mins])
        return result
    
  6. Task 5: SQL logical query evaluation order

    Even though we write SELECT first, SQL evaluates clauses logically in this sequence:

    1. FROM / JOIN   -> combine input tables and apply ON conditions
    2. WHERE         -> filter individual rows before grouping
    3. GROUP BY      -> bucket surviving rows into groups
    4. HAVING        -> filter groups based on aggregate results
    5. SELECT        -> compute aggregates (AVG, COUNT, SUM) and window functions
    6. DISTINCT      -> deduplicate output rows
    7. ORDER BY      -> sort the final result (followed by LIMIT / OFFSET)
    

    Concise takeaway on SQL's logical order: SQL evaluates clauses logically from FROM/JOIN through WHERE, GROUP BY, HAVING, SELECT, and finally ORDER BY, assembling joined rows well before projection aggregates run. Consequently, AVG() runs logically after JOIN across any multiplied rows — which is why Task 4 computes AVG(concurrent_viewers) in its own CTE prior to joining minute_viewed.

  7. Trace all four tasks on Example 1

    Running our logic on Example 1 (cat_keyword = 'rpg'):

    Task 1 (monthly_hours):
      2018-12: 1 row  -> 1/60 = 0.016666...
      2019-01: 2 rows -> 2/60 = 0.033333...
      2019-04: 3 rows -> 3/60 = 0.05
      2020-02: 1 row  -> 1/60 = 0.016666...
    
    Task 2 (streamer_category_totals, keyword = 'rpg'):
      nova : 4 total mins, 3 match ('ActionRPG', 'ActionRPG', 'rpg_maker') -> [nova, 4, 3, 0.75]
      pixel: 3 total mins, 1 matches ('RetroRPG')                          -> [pixel, 3, 1, 0.3333...]
    
    Task 3 (monthly_increases):
      nova  2018-12: 1 vs 2018-11 (0) -> keep [nova, 2018-12, 1, 0]
      nova  2019-01: 2 vs 2018-12 (1) -> keep [nova, 2019-01, 2, 1]  (crosses year boundary)
      nova  2020-02: 1 vs 2020-01 (0) -> keep [nova, 2020-02, 1, 0]  (empty Jan 2020 = 0)
      pixel 2019-04: 3 vs 2019-03 (0) -> keep [pixel, 2019-04, 3, 0]
    
    Task 4 (year_2019):
      nova : 2019 viewers [90, 110] -> avg 100.0; 2 US rows at 00:00 + 1 at 00:01 -> 3 viewer-mins, 2 unique mins
      pixel: 2019 viewers [30, 40, 50] -> avg 40.0; CA row at 18:00 skipped, 1 US row at 18:01 -> 1, 1
    
  8. Complete solution

    from typing import Any, Dict, List, Optional, Set, Tuple
    
    
    def normalize_timestamp(value: Any) -> str:
        """Normalize an ISO string (' ' or 'T') or datetime to 'YYYY-MM-DD HH:MM:SS'."""
        return str(value).replace("T", " ")[:19]
    
    
    def extract_year_month(value: Any) -> str:
        """Return 'YYYY-MM' so year boundaries stay distinct and text sort is chronological."""
        return normalize_timestamp(value)[:7]
    
    
    def prev_calendar_month(month_yyyy_mm: str) -> str:
        """Return the 'YYYY-MM' label of the immediately preceding calendar month."""
        year = int(month_yyyy_mm[:4])
        month = int(month_yyyy_mm[5:7])
        # January rolls back to December of the previous year.
        if month == 1:
            return f"{year - 1:04d}-12"
        return f"{year:04d}-{month - 1:02d}"
    
    
    def compute_monthly_hours(minute_streamed: List[Dict]) -> List[List]:
        """Task 1: total streamed hours per active 'YYYY-MM' across all streamers."""
        # month_minutes: {'2018-12': 1, '2019-01': 2, ...}
        month_minutes: Dict[str, int] = {}
        for row in minute_streamed:
            month = extract_year_month(row["time_minute"])
            month_minutes[month] = month_minutes.get(month, 0) + 1
    
        # 'YYYY-MM' strings sort chronologically across year boundaries.
        result: List[List] = []
        for month in sorted(month_minutes):
            result.append([month, month_minutes[month] / 60])
        return result
    
    
    def compute_streamer_category_totals(minute_streamed: List[Dict], cat_keyword: str) -> List[List]:
        """Task 2: per-streamer total minutes, keyword-matched minutes, and share."""
        needle = cat_keyword.lower()
        # total_minutes / keyword_minutes: {'nova': 4, 'pixel': 3, ...}
        total_minutes: Dict[str, int] = {}
        keyword_minutes: Dict[str, int] = {}
    
        for row in minute_streamed:
            name = row["streamer_username"]
            if name not in total_minutes:
                total_minutes[name] = 0
                keyword_minutes[name] = 0
    
            total_minutes[name] += 1
            category = row["category"]
            # Guard against None categories and match case-insensitively on both sides.
            if category is not None and needle in category.lower():
                keyword_minutes[name] += 1
    
        result: List[List] = []
        for name in sorted(total_minutes):
            share = keyword_minutes[name] / total_minutes[name]
            result.append([name, total_minutes[name], keyword_minutes[name], share])
        return result
    
    
    def compute_monthly_increases(minute_streamed: List[Dict]) -> List[List]:
        """Task 3: months where a streamer's minutes strictly beat the previous calendar month."""
        # streamer_month_minutes: {('nova', '2019-01'): 2, ...}
        streamer_month_minutes: Dict[Tuple[str, str], int] = {}
        for row in minute_streamed:
            key = (row["streamer_username"], extract_year_month(row["time_minute"]))
            streamer_month_minutes[key] = streamer_month_minutes.get(key, 0) + 1
    
        result: List[List] = []
        # Only active months can increase, because 0 > prev_minutes is impossible when prev >= 0.
        for streamer, month in sorted(streamer_month_minutes):
            current_mins = streamer_month_minutes[(streamer, month)]
            # Look up the previous calendar month (defaulting to 0 if inactive), NOT previous active month.
            prev_mins = streamer_month_minutes.get((streamer, prev_calendar_month(month)), 0)
            if current_mins > prev_mins:
                result.append([streamer, month, current_mins, prev_mins])
        return result
    
    
    def compute_year_2019_stats(minute_streamed: List[Dict], minute_viewed: List[Dict]) -> List[List]:
        """Task 4: 2019 avg concurrent viewers, US viewer-minutes, and distinct US minutes."""
        # Phase 1: aggregate 2019 broadcast stats from minute_streamed alone (prevents viewer fan-out).
        viewer_sum_2019: Dict[str, int] = {}
        stream_mins_2019: Dict[str, int] = {}
        # streamed_2019_keys: {('nova', '2019-01-01 00:00:00'), ...}
        streamed_2019_keys: Set[Tuple[str, str]] = set()
    
        for row in minute_streamed:
            moment = normalize_timestamp(row["time_minute"])
            if moment[:4] != "2019":
                continue
            name = row["streamer_username"]
            viewer_sum_2019[name] = viewer_sum_2019.get(name, 0) + row["concurrent_viewers"]
            stream_mins_2019[name] = stream_mins_2019.get(name, 0) + 1
            streamed_2019_keys.add((name, moment))
    
        # Phase 2: count US viewer-minutes that match a valid 2019 (streamer, minute) broadcast key.
        us_viewer_mins: Dict[str, int] = {}
        # us_distinct_moments: {'nova': {'2019-01-01 00:00:00', ...}}
        us_distinct_moments: Dict[str, Set[str]] = {}
    
        for row in minute_viewed:
            if row["viewer_country"] != "US":
                continue
            name = row["streamer_username"]
            moment = normalize_timestamp(row["time_minute"])
            # streamed_2019_keys contains only 2019 live minutes, filtering year and live match at once.
            if (name, moment) not in streamed_2019_keys:
                continue
            us_viewer_mins[name] = us_viewer_mins.get(name, 0) + 1
            if name not in us_distinct_moments:
                us_distinct_moments[name] = set()
            us_distinct_moments[name].add(moment)
    
        # Phase 3: left-join US stats onto every 2019 streamer so 0-US streamers stay included.
        result: List[List] = []
        for name in sorted(stream_mins_2019):
            avg_viewers = round(viewer_sum_2019[name] / stream_mins_2019[name], 4)
            total_us_rows = us_viewer_mins.get(name, 0)
            distinct_us_mins = len(us_distinct_moments.get(name, set()))
            result.append([name, avg_viewers, total_us_rows, distinct_us_mins])
        return result
    
    
    def streaming_analytics(minute_streamed: List[Dict], minute_viewed: List[Dict], cat_keyword: str) -> Dict:
        return {
            "monthly_hours": compute_monthly_hours(minute_streamed),
            "streamer_category_totals": compute_streamer_category_totals(minute_streamed, cat_keyword),
            "monthly_increases": compute_monthly_increases(minute_streamed),
            "year_2019": compute_year_2019_stats(minute_streamed, minute_viewed),
        }
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Imagine running analytics for a live-streaming platform using two logbooks kept at different grains (a table's grain is what a single row represents): - The broadcaster logbook (minute_streamed) writes one line per live minute of a streamer, noting the game category and total concurrent audience on the stream. - The viewer ticket logbook (minute_viewed) writes one line per viewer per minute, noting who watched whom and from which country.

Every tricky part of this problem comes down to respecting calendar gaps and table grains. Three naive SQL shortcuts fail immediately: 1. Grouping by month number (1..12) instead of 'YYYY-MM' merges December 2018 and December 2019 into one bucket. 2. Using a bare LAG(minutes) window function (a SQL function that inspects neighboring rows in a sorted partition without collapsing rows) compares a streamer's March 2020 activity against their last active month in January 2019, skipping February 2020 (0 minutes) instead of counting March as an increase over 0. 3. Joining minute_streamed directly to minute_viewed before taking AVG(concurrent_viewers) causes join fan-out (one row on the left multiplying into many rows on the right): a minute watched by 5 viewers gets counted 5 times in the average, skewing the streamer's concurrency toward crowded minutes!

Instead, we bucket months as 'YYYY-MM', compare each active (streamer, month) against its exact preceding calendar month via a LEFT JOIN (a join that keeps every left-side row and fills unmatched right-side columns with NULL) or dictionary lookup with default 0, and use Common Table Expressions, or CTEs (named temporary subqueries introduced with WITH) to aggregate minute_streamed at the broadcast-minute grain before joining minute_viewed on (streamer_username, time_minute).

Trace a tiny 2-minute example for streamer c in 2019: - minute_streamed: 00:00 (10 viewers), 00:01 (40 viewers). From minute_streamed alone, avg_concurrent_viewers_2019 = (10 + 40) / 2 = 25.0. - minute_viewed: 5 US viewers watch c at 00:00, and 0 US viewers watch at 00:01. Matching against c's 2019 live keys {('c', '00:00'), ('c', '00:01')} yields 5 total us_viewer_minutes_2019 and 1 unique_streaming_minutes_with_us_2019 (00:00 only) — without distorting the 25.0 average!

Complexity

Let S be the number of rows in minute_streamed and V be the number of rows in minute_viewed.

  • Time (Python): O(S log S + V). Each of Tasks 1–4 scans the S rows of minute_streamed once with O(1) hash-table updates; Task 4 scans the V rows of minute_viewed once doing an O(1) set lookup in streamed_2019_keys; sorting the grouped keys (at most S distinct months, streamers, or (streamer, month) pairs) takes O(S log S) time.
  • Space (Python): O(S). Every dictionary and set (month_minutes, streamer_month_minutes, streamed_2019_keys, and us_distinct_moments, which is a subset of streamed_2019_keys) stores at most S entries.
  • SQL scaling & indexes: Tasks 1–3 each scan minute_streamed once (O(S) with hash aggregation), and Task 3's self-join operates on the tiny aggregated monthly CTE rather than raw minutes. Task 4 is dominated by scanning US rows of the larger minute_viewed table (O(S + V) with a hash join); partitioning both tables by date and indexing (streamer_username, time_minute) lets the half-open range time_minute >= '2019-01-01' AND time_minute < '2020-01-01' skip all non-2019 data cleanly.

Edge cases

  • Inactive calendar months: Task 1 outputs only months present in minute_streamed (matching Example 1, which omits inactive months like 2019-02), whereas Task 3 treats an absent preceding calendar month as 0 minutes.
  • Year boundaries and strict inequality: prev_calendar_month('2019-01') rolls back to '2018-12', and current_mins > prev_mins excludes months where minutes stayed equal (3 vs 3).
  • Case-insensitive and NULL categories: Lower-casing both category and cat_keyword matches 'cHaT' inside 'Just Chatting' or 'speedchat', ignores None/NULL categories safely, and treats wildcard characters like '%' literally.
  • 2019 streamers with zero US viewers: Kept in year_2019 with 0 US viewer-minutes and 0 unique US minutes thanks to the LEFT JOIN (or iterating sorted(stream_mins_2019) in Python); streamers active only in 2018 or 2020 do not appear in year_2019.
  • Unmatched viewer rows: Viewer tickets for non-US countries, other years, or minutes when the streamer was not live in minute_streamed are ignored.

Common mistakes

  • Integer division in SQL: Writing COUNT(*) / 60 or SUM(is_keyword) / COUNT(*) truncates decimals to 0 in PostgreSQL and SQLite; multiply by 1.0 or divide by 60.0.
  • Using bare LAG() for previous calendar month: LAG() looks at the previous active row, silently skipping empty months and missing real increases after a hiatus.
  • Subtracting 1 month from end-of-month timestamps: In SQLite, DATE('2019-03-31', '-1 month') normalizes '2019-02-31' into '2019-03-03'! Always truncate to 'start of month' (YYYY-MM-01) before doing month arithmetic.
  • Averaging concurrent_viewers after joining minute_viewed: Multiplies each broadcast minute by its viewer rows (giving nova 96.6667 instead of 100.0 on Example 1).
  • Filtering WHERE v.viewer_country = 'US' after a LEFT JOIN: Because unmatched rows have v.viewer_country = NULL, a WHERE filter discards them and silently turns the LEFT JOIN into an INNER JOIN! Filter inside a CTE before left-joining, or inside the ON clause.
  • Using BETWEEN '2019-01-01' AND '2019-12-31' on timestamps: '2019-12-31' defaults to 00:00:00, dropping 23 hours and 59 minutes of New Year's Eve! Always use a half-open interval (>= '2019-01-01' AND < '2020-01-01').

Follow-up questions

  • In SQL's logical evaluation sequence, is AVG() computed before or after JOIN, and why does that matter for concurrency metrics? SQL logically processes clauses in the order FROM / JOIN -> WHERE -> GROUP BY -> HAVING -> SELECT -> ORDER BY, meaning AVG() in SELECT runs after JOIN has already multiplied left-table rows by matching right-table rows. If you join minute_streamed to minute_viewed first, minutes watched by many viewers get repeated in the average (fan-out), so you must compute AVG(concurrent_viewers) inside a separate CTE before joining viewer rows.
  • How would you change the monthly hours SQL query so calendar months with zero broadcasts still show up with 0.0 hours? Build a spine of every calendar month between the earliest and latest timestamp using a recursive CTE (a CTE that repeatedly adds 1 month to its previous row until reaching the end month; in PostgreSQL you can use generate_series(first_month, last_month, INTERVAL '1 month')), then LEFT JOIN minute_streamed onto that month spine and use COUNT(s.time_minute) / 60.0 so unmatched months evaluate to 0.0:

sql WITH RECURSIVE bounds AS ( SELECT DATE(MIN(time_minute), 'start of month') AS first_month, DATE(MAX(time_minute), 'start of month') AS last_month FROM minute_streamed ), months(month_start) AS ( SELECT first_month FROM bounds WHERE first_month IS NOT NULL UNION ALL SELECT DATE(month_start, '+1 month') FROM months, bounds WHERE month_start < last_month ) SELECT strftime('%Y-%m', m.month_start) AS month_yyyy_mm, COUNT(s.time_minute) / 60.0 AS hours_streamed FROM months AS m LEFT JOIN minute_streamed AS s ON DATE(s.time_minute, 'start of month') = m.month_start GROUP BY m.month_start ORDER BY m.month_start;

  • Can you detect month-over-month increases using LAG() instead of a self-join while still treating skipped calendar months as 0? Yes! Inside a window ordered by month_start, check both LAG(month_start) and LAG(minutes): if LAG(month_start) equals DATE(month_start, '-1 month'), use LAG(minutes) as prev_minutes; otherwise the immediately preceding calendar month had no activity, so set prev_minutes = 0. That scans the monthly CTE once with a single window sort instead of a hash self-join.
  • Which partitioning, clustering, and rollup strategies keep these queries fast once viewer logs reach billions of rows? minute_viewed grows orders of magnitude faster than minute_streamed (for example, 10,000 concurrent viewers produce 10,000 minute_viewed rows per single minute_streamed row). In production, partition both tables by date (YYYY-MM-DD) so year/month predicates prune unneeded partitions, cluster both tables by (streamer_username, time_minute) so co-located hash/merge joins avoid shuffling the whole cluster, and maintain an incremental daily/monthly rollup table per creator so Tasks 1–3 and avg_concurrent_viewers read kilobytes of pre-aggregated summaries instead of scanning raw minute logs.

Follow-up questions

Similar questions

More Twitch interview questions

All 5 Twitch questions →