Analyze Live Streaming Telemetry and Viewing Events
SQL & DataAuto-graded · 16 test casesLast updated
Process minute-level streaming activity and viewer events to calculate time-series metrics, category shares, month-over-month growth, and joined yearly summaries.
You are tasked with analyzing telemetry logs from a live streaming platform. You are given two lists of dictionaries representing minute-by-minute streaming sessions and individual viewing logs:
-
minute_streamed: A list of records where each entry represents one minute a creator was actively streaming:time_minute(str): ISO timestamp string (e.g.,'2019-01-01T00:00:00'or'2019-01-01 00:00:00').streamer_username(str): Unique name of the streamer.category(str): Content category for that minute.concurrent_viewers(int): Number of active viewers at that minute.
-
minute_viewed: A list of records where each entry represents one minute spent by a viewer watching a streamer:time_minute(str): Timestamp of the viewing event.viewer_username(str): Unique name of the viewer.viewer_country(str): Country code of the viewer (e.g.,'US').streamer_username(str): Streamer being watched.
Write a Python function analyze_streaming_data that takes minute_streamed, minute_viewed, and a substring cat_keyword (str), and returns a dictionary with four specific summary datasets:
1. monthly_hours
- Aggregate total streaming activity across all creators per calendar month formatted as
'YYYY-MM'. - Calculate total hours streamed (
minutes / 60.0). - Return a list of lists:
[[month_str, total_hours], ...], sorted chronologically bymonth_str.
2. streamer_category_totals
- For every streamer present in
minute_streamed, count:total_minutes: Total minutes streamed.keyword_minutes: Minutes wherecategorycontainscat_keyword(case-insensitive substring match).keyword_share: Ratiokeyword_minutes / total_minutes(0 if total is 0).
- Return a list of lists:
[[streamer_username, total_minutes, keyword_minutes, keyword_share], ...], sorted alphabetically bystreamer_username.
3. monthly_increases
- For each streamer and calendar month where they streamed, determine if their active minutes in that month strictly exceeded their active minutes in the immediately preceding calendar month (e.g.,
'2019-01'compares against'2018-12'). - If the streamer had no streamed minutes in the preceding calendar month, count that preceding month's minutes as
0. - Return a list of lists:
[[streamer_username, month_str, current_minutes, prev_minutes], ...], containing only months wherecurrent_minutes > prev_minutes. - Order the output by
streamer_usernameascending, thenmonth_strascending.
4. year_2019
- Consider only streamers who logged at least one streamed minute during the year 2019.
- Compute:
avg_concurrent: Average ofconcurrent_viewersacross all minutes streamed by that creator in 2019 (usingminute_streamedonly).us_viewer_minutes: Total count of viewer-minute logs inminute_viewedfromviewer_country == 'US'during 2019 for that streamer, matching only timestamp minutes where the streamer was active inminute_streamed.us_unique_minutes: The number of distinct streaming timestamps in 2019 where the streamer was active and had at least one US viewer log inminute_viewed.
- Return a list of lists:
[[streamer_username, avg_concurrent, us_viewer_minutes, us_unique_minutes], ...], sorted alphabetically bystreamer_username.
Constraints
- Timestamps are formatted as ISO string timestamps (space or
'T'separator). - Matching of
cat_keywordis case-insensitive. Country code matching is exact ('US'). - Floating point values are standard 64-bit floats.
Examples
Example 1
Input: analyze_streaming_data([{'time_minute': '2018-12-31T23:59:00', 'streamer_username': 'aaa', 'category': 'TTBHGD', 'concurrent_viewers': 100}, {'time_minute': '2019-01-01T00:00:00', 'streamer_username': 'aaa', 'category': 'TTBHGD', 'concurrent_viewers': 120}, {'time_minute': '2019-01-01T00:01:00', 'streamer_username': 'aaa', 'category': 'TTBHGD', 'concurrent_viewers': 130}, {'time_minute': '2019-03-15T09:00:00', 'streamer_username': 'bbb', 'category': 'VGDH', 'concurrent_viewers': 50}, {'time_minute': '2019-03-15T09:01:00', 'streamer_username': 'bbb', 'category': 'VGDH', 'concurrent_viewers': 60}, {'time_minute': '2019-03-31T22:15:00', 'streamer_username': 'bbb', 'category': 'CCVF', 'concurrent_viewers': 70}, {'time_minute': '2020-03-19T13:00:00', 'streamer_username': 'aaa', 'category': 'TTBHGD', 'concurrent_viewers': 133}, {'time_minute': '2020-03-19T13:01:00', 'streamer_username': 'aaa', 'category': 'TTBHGD', 'concurrent_viewers': 45}], [{'time_minute': '2019-01-01T00:00:00', 'viewer_username': 'ccc', 'viewer_country': 'US', 'streamer_username': 'aaa'}, {'time_minute': '2019-01-01T00:01:00', 'viewer_username': 'ccc', 'viewer_country': 'US', 'streamer_username': 'aaa'}, {'time_minute': '2019-03-15T09:00:00', 'viewer_username': 'ddd', 'viewer_country': 'JP', 'streamer_username': 'bbb'}, {'time_minute': '2019-03-15T09:00:00', 'viewer_username': 'eee', 'viewer_country': 'US', 'streamer_username': 'bbb'}, {'time_minute': '2019-03-15T09:01:00', 'viewer_username': 'eee', 'viewer_country': 'US', 'streamer_username': 'bbb'}, {'time_minute': '2019-03-31T22:15:00', 'viewer_username': 'fff', 'viewer_country': 'US', 'streamer_username': 'bbb'}, {'time_minute': '2020-03-19T13:00:00', 'viewer_username': 'ccc', 'viewer_country': 'US', 'streamer_username': 'aaa'}], 'TTB')
Output: {'monthly_hours': [['2018-12', 0.016666666666666666], ['2019-01', 0.03333333333333333], ['2019-03', 0.05], ['2020-03', 0.03333333333333333]], 'streamer_category_totals': [['aaa', 5, 5, 1], ['bbb', 3, 0, 0]], 'monthly_increases': [['aaa', '2018-12', 1, 0], ['aaa', '2019-01', 2, 1], ['aaa', '2020-03', 2, 0], ['bbb', '2019-03', 3, 0]], 'year_2019': [['aaa', 125, 2, 2], ['bbb', 60, 3, 3]]}
Hints
Hint 1
For month-over-month comparisons, remember that the previous calendar month for 'YYYY-01' is '(YYYY-1)-12'.
Hint 2
When filtering viewer minutes in Task 4, verify that the streamer was actually live at that exact timestamp minute.
Hint 3
Ensure keyword substring matching converts both the category and keyword to lowercase.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The problem requires extracting four distinct aggregated metrics from streaming and viewing telemetry events:
-
Monthly Hours: Parse timestamps to extract the
YYYY-MMmonth key. Accumulate counts of minute logs per month, convert minutes to hours (/ 60.0), and sort chronologically. -
Category Keyword Share: Group
minute_streamedbystreamer_username. Track total streaming minutes alongside minutes matchingcat_keywordusing lowercase comparison. Computekeyword_share = keyword_minutes / total_minutes. -
Month-over-Month Growth: For each streamer, calculate active minutes per active calendar month. To find the previous month, parse the year and month components: if month is 1, the previous month is
(year - 1)-12, otherwiseyear-(month - 1). Fetch previous month's minutes (defaulting to 0 if missing) and filter wherecurrent_minutes > prev_minutes. -
2019 Streamer Metrics & Joins: Filter
minute_streamedfor entries in year 2019, tracking each streamer'sconcurrent_viewershistory and set of active minute timestamps. Forminute_viewedentries in 2019 with country'US', verify the streamer was active at that minute timestamp. Count total US viewer entries and unique active timestamps with US viewers.
Complexity
- Time Complexity: $\mathcal{O}(N + M)$, where $N$ is the number of records in
minute_streamedand $M$ is the number of records inminute_viewed. Grouping, filtering, and lookup operations run in linear time, while final sorts operate on small aggregate lists. - Space Complexity: $\mathcal{O}(N + M)$ to store hash maps and timestamp sets for aggregations.
from typing import List, Dict
from datetime import datetime
from collections import defaultdict
def analyze_streaming_data(minute_streamed: List[dict], minute_viewed: List[dict], cat_keyword: str) -> dict:
# Task 1: Monthly hours streamed
monthly_minutes = defaultdict(int)
for row in minute_streamed:
dt = datetime.fromisoformat(row['time_minute'].replace('T', ' '))
month_key = dt.strftime('%Y-%m')
monthly_minutes[month_key] += 1
monthly_hours = sorted([[month, mins / 60.0] for month, mins in monthly_minutes.items()])
# Task 2: Streamer category totals with keyword
streamer_totals = defaultdict(int)
streamer_keyword = defaultdict(int)
cat_keyword_lower = cat_keyword.lower()
for row in minute_streamed:
streamer = row['streamer_username']
category = row['category']
streamer_totals[streamer] += 1
if cat_keyword_lower in category.lower():
streamer_keyword[streamer] += 1
streamer_category_totals = []
for streamer in sorted(streamer_totals.keys()):
total = streamer_totals[streamer]
keyword = streamer_keyword.get(streamer, 0)
share = keyword / total if total > 0 else 0.0
streamer_category_totals.append([streamer, total, keyword, share])
# Task 3: Monthly increases
streamer_monthly = defaultdict(lambda: defaultdict(int))
for row in minute_streamed:
dt = datetime.fromisoformat(row['time_minute'].replace('T', ' '))
month_key = dt.strftime('%Y-%m')
streamer = row['streamer_username']
streamer_monthly[streamer][month_key] += 1
monthly_increases = []
for streamer in sorted(streamer_monthly.keys()):
months = sorted(streamer_monthly[streamer].items())
for month, current_mins in months:
year, month_num = map(int, month.split('-'))
if month_num == 1:
prev_month_key = f"{year - 1}-12"
else:
prev_month_key = f"{year}-{month_num - 1:02d}"
prev_mins = streamer_monthly[streamer].get(prev_month_key, 0)
if current_mins > prev_mins:
monthly_increases.append([streamer, month, current_mins, prev_mins])
# Task 4: Year 2019 analytics
streamer_2019_concurrent = defaultdict(list)
streamer_2019_minutes = defaultdict(set)
for row in minute_streamed:
dt = datetime.fromisoformat(row['time_minute'].replace('T', ' '))
if dt.year == 2019:
streamer = row['streamer_username']
streamer_2019_concurrent[streamer].append(row['concurrent_viewers'])
streamer_2019_minutes[streamer].add(row['time_minute'])
streamer_us_minutes = defaultdict(int)
streamer_us_unique_minutes = defaultdict(set)
for row in minute_viewed:
dt = datetime.fromisoformat(row['time_minute'].replace('T', ' '))
if dt.year == 2019 and row['viewer_country'] == 'US':
streamer = row['streamer_username']
time_minute = row['time_minute']
if time_minute in streamer_2019_minutes[streamer]:
streamer_us_minutes[streamer] += 1
streamer_us_unique_minutes[streamer].add(time_minute)
year_2019 = []
for streamer in sorted(streamer_2019_concurrent.keys()):
avg_concurrent = sum(streamer_2019_concurrent[streamer]) / len(streamer_2019_concurrent[streamer])
us_minutes = streamer_us_minutes.get(streamer, 0)
us_unique_minutes = len(streamer_us_unique_minutes.get(streamer, set()))
year_2019.append([streamer, avg_concurrent, us_minutes, us_unique_minutes])
return {
"monthly_hours": monthly_hours,
"streamer_category_totals": streamer_category_totals,
"monthly_increases": monthly_increases,
"year_2019": year_2019
}