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, andcategorymay beNone)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:
"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 bymonth_yyyy_mm."streamer_category_totals": For each creator inminute_streamed, return[streamer_username, total_minutes, keyword_minutes, keyword_share]sorted ascending bystreamer_username, wherekeyword_minutescounts broadcast minutes whose non-nullcategorycontainscat_keyword(case-insensitive substring match) andkeyword_share = keyword_minutes / total_minutes."monthly_increases": For each creator and active month"YYYY-MM", compare their streamed minutescurrent_minutesagainstprev_minutesin the immediately preceding calendar month (treating an unstreamed prior calendar month as0minutes, and rolling"YYYY-01"back to"(YYYY-1)-12"). Return[streamer_username, month_yyyy_mm, current_minutes, prev_minutes]only wherecurrent_minutes > prev_minutes, sorted ascending by(streamer_username, month_yyyy_mm)."year_2019": Restricted to calendar year2019, for every creator with at least one2019row inminute_streamed, return[streamer_username, avg_concurrent_viewers_2019, us_viewer_minutes_2019, unique_streaming_minutes_with_us_2019]sorted ascending bystreamer_username:avg_concurrent_viewers_2019: mean ofconcurrent_viewersacross that creator's2019rows inminute_streamedalone (not weighted by viewer rows), rounded to4decimal places.us_viewer_minutes_2019: total2019rows inminute_viewedwithviewer_country == "US"whose(streamer_username, time_minute)matches a2019row inminute_streamed(0if none).unique_streaming_minutes_with_us_2019: number of distinct2019broadcast minutes for that creator inminute_streamedwith at least one matching"US"viewer row (0if 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^5time_minuteis a valid UTC timestamp string ("YYYY-MM-DDTHH:MM:SS"or"YYYY-MM-DD HH:MM:SS")0 <= concurrent_viewers <= 10^7categoryisstrorNone;0 <= len(cat_keyword) <= 100
Step-by-step walkthrough
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 watchnovaduring the same minute,minute_streamedhas 1 row whileminute_viewedhas 5 rows.
For the automated Python judge,
streaming_analytics(minute_streamed, minute_viewed, cat_keyword)receives both tables as lists of dictionaries pluscat_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 streamerBelow 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.
Task 1: bucket minutes by YYYY-MM so years stay separate
Each row in
minute_streamedequals 1 minute streamed, so hours equalCOUNT(*) / 60.0(using60.0instead of integer60prevents SQL integer division from truncating2 / 60to0).Crucially, we must group by both year and month formatted as
'YYYY-MM'. Grouping byEXTRACT(MONTH FROM time_minute)alone would merge2018-12and2019-12into 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 resultTask 2: compute case-insensitive category keyword share
For each streamer, we want
total_minutes,keyword_minutes(minutes whosecategorycontainscat_keywordignoring letter case), andkeyword_share = keyword_minutes / total_minutes.In SQL,
LIKEis case-sensitive in PostgreSQL and treats%and_insidecat_keywordas wildcards. Lower-casing both strings and testing substring position withINSTR(LOWER(category), LOWER(:cat_keyword)) > 0(PostgreSQL:POSITION(LOWER(:cat_keyword) IN LOWER(category)) > 0) handles mixed case portably, treats%/_literally, and turnsNULLcategories safely into0viaCASE.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 resultTask 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
novain 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 day01so 31-day months never overflow! 2.LEFT JOINthat monthly table (cur) to itself (prev) on the same streamer andprev.month_start = cur.month_start - 1 month. When the streamer did not stream in the previous calendar month,prev.minutesisNULL, whichCOALESCE(prev.minutes, 0)turns into0. 3. Why don't we need rows wherecur.minutes = 0? Becauseprev_minutes >= 0, so0 > prev_minutescan 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 resultTask 4: aggregate before joining to avoid viewer fan-out
Why can't we simply
LEFT JOIN minute_streamed TO minute_viewedand computeAVG(concurrent_viewers)andCOUNT(US viewers)in oneGROUP BY? Look at what happens to creatornovain 2019 when two viewers (v_amyandv_ben) watch the00:00minute: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: computeAVG(concurrent_viewers)per streamer fromminute_streamedalone in 2019. 2.us_2019: joinminute_viewed(viewer_country = 'US') againstSELECT DISTINCT streamer_username, time_minute FROM minute_streamedin 2019, countingCOUNT(*)for total US viewer-minutes andCOUNT(DISTINCT v.time_minute)for unique broadcast minutes with at least one US viewer. 3.LEFT JOINus_2019ontoavg_2019withCOALESCE(..., 0)so 2019 streamers with zero US viewers still appear with0, 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 resultTask 5: SQL logical query evaluation order
Even though we write
SELECTfirst, 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/JOINthroughWHERE,GROUP BY,HAVING,SELECT, and finallyORDER BY, assembling joined rows well before projection aggregates run. Consequently,AVG()runs logically afterJOINacross any multiplied rows — which is why Task 4 computesAVG(concurrent_viewers)in its own CTE prior to joiningminute_viewed.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, 1Complete 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
Srows ofminute_streamedonce with O(1) hash-table updates; Task 4 scans theVrows ofminute_viewedonce doing an O(1) set lookup instreamed_2019_keys; sorting the grouped keys (at mostSdistinct 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, andus_distinct_moments, which is a subset ofstreamed_2019_keys) stores at mostSentries. - SQL scaling & indexes: Tasks 1–3 each scan
minute_streamedonce (O(S)with hash aggregation), and Task 3's self-join operates on the tiny aggregatedmonthlyCTE rather than raw minutes. Task 4 is dominated by scanning US rows of the largerminute_viewedtable (O(S + V)with a hash join); partitioning both tables by date and indexing(streamer_username, time_minute)lets the half-open rangetime_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 like2019-02), whereas Task 3 treats an absent preceding calendar month as0minutes. - Year boundaries and strict inequality:
prev_calendar_month('2019-01')rolls back to'2018-12', andcurrent_mins > prev_minsexcludes months where minutes stayed equal (3vs3). - Case-insensitive and
NULLcategories: Lower-casing bothcategoryandcat_keywordmatches'cHaT'inside'Just Chatting'or'speedchat', ignoresNone/NULLcategories safely, and treats wildcard characters like'%'literally. - 2019 streamers with zero US viewers: Kept in
year_2019with0US viewer-minutes and0unique US minutes thanks to theLEFT JOIN(or iteratingsorted(stream_mins_2019)in Python); streamers active only in 2018 or 2020 do not appear inyear_2019. - Unmatched viewer rows: Viewer tickets for non-US countries, other years, or minutes when the streamer was not live in
minute_streamedare ignored.
Common mistakes
- Integer division in SQL: Writing
COUNT(*) / 60orSUM(is_keyword) / COUNT(*)truncates decimals to0in PostgreSQL and SQLite; multiply by1.0or divide by60.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_viewersafter joiningminute_viewed: Multiplies each broadcast minute by its viewer rows (givingnova96.6667instead of100.0on Example 1). - Filtering
WHERE v.viewer_country = 'US'after aLEFT JOIN: Because unmatched rows havev.viewer_country = NULL, aWHEREfilter discards them and silently turns theLEFT JOINinto anINNER JOIN! Filter inside a CTE before left-joining, or inside theONclause. - Using
BETWEEN '2019-01-01' AND '2019-12-31'on timestamps:'2019-12-31'defaults to00: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 afterJOIN, and why does that matter for concurrency metrics? SQL logically processes clauses in the orderFROM / JOIN->WHERE->GROUP BY->HAVING->SELECT->ORDER BY, meaningAVG()inSELECTruns afterJOINhas already multiplied left-table rows by matching right-table rows. If you joinminute_streamedtominute_viewedfirst, minutes watched by many viewers get repeated in the average (fan-out), so you must computeAVG(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.0hours? 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 usegenerate_series(first_month, last_month, INTERVAL '1 month')), thenLEFT JOINminute_streamedonto that month spine and useCOUNT(s.time_minute) / 60.0so unmatched months evaluate to0.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 as0? Yes! Inside a window ordered bymonth_start, check bothLAG(month_start)andLAG(minutes): ifLAG(month_start)equalsDATE(month_start, '-1 month'), useLAG(minutes)asprev_minutes; otherwise the immediately preceding calendar month had no activity, so setprev_minutes = 0. That scans themonthlyCTE 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_viewedgrows orders of magnitude faster thanminute_streamed(for example, 10,000 concurrent viewers produce 10,000minute_viewedrows per singleminute_streamedrow). 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 andavg_concurrent_viewersread kilobytes of pre-aggregated summaries instead of scanning raw minute logs.
Follow-up questions
- In SQL's logical evaluation sequence, is `AVG()` computed before or after `JOIN`, and why does that matter for concurrency metrics?
- How would you change the monthly hours SQL query so calendar months with zero broadcasts still show up with `0.0` hours?
- Can you detect month-over-month increases using `LAG()` instead of a self-join while still treating skipped calendar months as `0`?
- Which partitioning, clustering, and rollup strategies keep these queries fast once viewer logs reach billions of rows?
Similar questions
- Chronological Broadcast Hours per Calendar Month
- Real-Time Live Broadcast Recommender System
- Role Motivation and Data Science Behavioral Scenarios
- Implement Four Standalone Stateful Coding Utilities
- Job Posting Engagement Metrics Excluding Non-Viewing Applicants
- Compute 7-Day DAU, D1 Retention, and Revenue Cohorts