Per-Stream Playback Event Tallies
Easy · Software Engineering Fundamentals · Data Scientist · Technical Screen
Problem Statement
A live-video analytics pipeline stores broadcast metadata and viewer play logs across two relational tables:
streamsstream_id(INTEGER): primary key uniquely identifying each broadcast session.streamer_name(VARCHAR): handle or display name of the creator running that session.
playback_eventsevent_id(INTEGER): primary key uniquely identifying an individual play log entry.stream_id(INTEGER): identifier referencing the broadcast session played.
Produce one summary row for every session in streams with three fields — stream_id, streamer_name, and event_count — reporting how many playback_events records reference that session:
- Every row from
streamsmust appear in the output, showingevent_count = 0whenever a session has zero matching play logs. - Play logs whose
stream_iddoes not match any row instreamsare ignored. - Output rows may appear in any order.
In SQL, return a result set with columns (stream_id, streamer_name, event_count). In Python, implement calculate_playback_counts(streams: List[Dict], playback_events: List[Dict]) -> List[Dict], where each input and output table is represented as a list of row dictionaries.
Examples
Example 1
Input tables:
streams:
| stream_id | streamer_name |
|---|---|
| 501 | Nora |
| 502 | Omar |
playback_events:
| event_id | stream_id |
|---|---|
| 10 | 502 |
| 11 | 501 |
| 12 | 502 |
| 13 | 502 |
Output:
| stream_id | streamer_name | event_count |
|---|---|---|
| 501 | Nora | 1 |
| 502 | Omar | 3 |
Python call:
streams = [{"stream_id": 501, "streamer_name": "Nora"}, {"stream_id": 502, "streamer_name": "Omar"}]
playback_events = [
{"event_id": 10, "stream_id": 502},
{"event_id": 11, "stream_id": 501},
{"event_id": 12, "stream_id": 502},
{"event_id": 13, "stream_id": 502}
]
Output -> [{"stream_id": 501, "streamer_name": "Nora", "event_count": 1}, {"stream_id": 502, "streamer_name": "Omar", "event_count": 3}]
Explanation: Session 501 (Nora) matches one play event (11), while session 502 (Omar) matches three play events (10, 12, 13).
Example 2
Input tables:
streams:
| stream_id | streamer_name |
|---|---|
| 710 | Priya |
| 720 | Quinn |
| 730 | Ravi |
playback_events:
| event_id | stream_id |
|---|---|
| 21 | 720 |
| 22 | 720 |
Output:
| stream_id | streamer_name | event_count |
|---|---|---|
| 710 | Priya | 0 |
| 720 | Quinn | 2 |
| 730 | Ravi | 0 |
Python call:
streams = [
{"stream_id": 710, "streamer_name": "Priya"},
{"stream_id": 720, "streamer_name": "Quinn"},
{"stream_id": 730, "streamer_name": "Ravi"}
]
playback_events = [{"event_id": 21, "stream_id": 720}, {"event_id": 22, "stream_id": 720}]
Output -> [
{"stream_id": 710, "streamer_name": "Priya", "event_count": 0},
{"stream_id": 720, "streamer_name": "Quinn", "event_count": 2},
{"stream_id": 730, "streamer_name": "Ravi", "event_count": 0}
]
Explanation: Only session 720 (Quinn) has recorded plays (2); sessions 710 (Priya) and 730 (Ravi) have no matching rows in playback_events, so both still appear with event_count = 0.
Constraints
0 <= len(streams) <= 10^5, andstream_idvalues instreamsare distinct integers.0 <= len(playback_events) <= 10^5, andevent_idvalues inplayback_eventsare distinct integers.- Multiple rows in
streamsmay share the samestreamer_name(one creator hosting several sessions), and each session must remain a separate output row. - Output row order does not matter.
Step-by-step walkthrough
Restate the problem
We have two relational tables from a live-video analytics pipeline:
streams: one row per broadcast session, withstream_id(the unique identifier, or primary key, of each session) andstreamer_name.playback_events: one row per play log entry, withevent_id(unique per event) andstream_id(recording which session was played).
We need one summary row for every session in
streamscontainingstream_id,streamer_name, andevent_count(how many play events referenced that session). When a session has zero play events, it must still appear in the output withevent_count = 0.Because this workspace runs both as a SQL question and with an automated Python judge, we will first build the SQL query step by step, and then implement the identical relational steps in
calculate_playback_counts(streams, playback_events)where each table is a list of row dictionaries:streams = [{"stream_id": 501, "streamer_name": "Nora"}, ...] playback_events = [{"event_id": 10, "stream_id": 502}, ...] output = [{"stream_id": 501, "streamer_name": "Nora", "event_count": 1}, ...]Why INNER JOIN and COUNT(*) fail on zero-event streams
Suppose
streamshas Priya (710), Quinn (720), and Ravi (730), whileplayback_eventshas two plays on session720and none at all on710or730(Example 2).Compare what happens when we join the two tables on
stream_id:INNER JOIN (drops unmatched streams!): +-------------+---------------+----------+-----------+ | s.stream_id | streamer_name | event_id | stream_id | +-------------+---------------+----------+-----------+ | 720 | Quinn | 21 | 720 | | 720 | Quinn | 22 | 720 | +-------------+---------------+----------+-----------+ --> Priya (710) and Ravi (730) vanished completely! LEFT JOIN from streams (keeps every stream!): +-------------+---------------+----------+-----------+ | s.stream_id | streamer_name | event_id | stream_id | +-------------+---------------+----------+-----------+ | 710 | Priya | NULL | NULL | | 720 | Quinn | 21 | 720 | | 720 | Quinn | 22 | 720 | | 730 | Ravi | NULL | NULL | +-------------+---------------+----------+-----------+Notice the two subtle rules revealed by the
LEFT JOINtable above:- Start from
streamsandLEFT JOIN playback_events: a left join keeps every row from the left table (streams) even when nothing matches on the right (playback_events), filling the unmatched right-side columns withNULL. - Use
COUNT(e.event_id), neverCOUNT(*): in SQL,COUNT(*)counts rows (including rows padded withNULLs), soCOUNT(*)would report1play for Priya and1play for Ravi! By contrast,COUNT(column)counts only non-NULLvalues in that column, soCOUNT(e.event_id)skipsNULLand accurately returns0for Priya and Ravi.
- Start from
Write the SQL query
Finally, we group the joined rows by
s.stream_idands.streamer_name:- Grouping by
s.stream_idensures that if Nora hosted two separate sessions (saystream_id = 1andstream_id = 2), each session keeps its own row instead of merging together under'Nora'. - Including
s.streamer_namealongsides.stream_idinGROUP BYsatisfies standard SQL's rule that every non-aggregatedSELECTcolumn must appear inGROUP BY(sincestream_iduniquely determinesstreamer_name, addingstreamer_namenever splits a group).
SELECT s.stream_id, s.streamer_name, -- Count non-NULL event_ids so unmatched LEFT JOIN rows produce 0, not 1. COUNT(e.event_id) AS event_count FROM streams AS s -- LEFT JOIN keeps streams that have zero rows in playback_events. LEFT JOIN playback_events AS e ON e.stream_id = s.stream_id -- Group per stream (stream_id is unique; streamer_name is functionally dependent on it). GROUP BY s.stream_id, s.streamer_name;- Grouping by
From SQL to Python: avoid O(S * E) nested loops
In Python, the brute-force way to compute
event_countis: for each of theSstreams, loop through allEplayback events and count how many share the samestream_id. That works on tiny inputs, but it performsS * Ecomparisons — with100,000streams and1,000,000events, that is100,000,000,000iterations.Instead, we do what a database query engine does when executing a hash aggregation + left join:
playback_events streams (21, 720) \ (710, "Priya") --> lookup 710 -> 0 (default) (22, 720) +--> event_counts_by_stream (720, "Quinn") --> lookup 720 -> 2 { 720: 2 } (730, "Ravi") --> lookup 730 -> 0 (default)- Phase 1 (
GROUP BY stream_id): scanplayback_eventsonce and tally counts in a dictionaryevent_counts_by_streaminO(E)time. - Phase 2 (
LEFT JOINfromstreams): scanstreamsonce and look up eachstream_idinevent_counts_by_stream(defaulting to0if absent) inO(S)time.
- Phase 1 (
Code Phase 1: tally playback events in one pass
Each event dictionary has
"stream_id". Usingevent_counts_by_stream.get(stream_id, 0)returns0the first time we see astream_idand its running tally thereafter:from typing import Any, Dict, List def count_events_by_stream(playback_events: List[Dict]) -> Dict[Any, int]: """Phase 1 (SQL GROUP BY stream_id): count playback events per stream_id.""" # event_counts_by_stream maps stream_id -> total event count, e.g. {501: 1, 502: 3}. event_counts_by_stream: Dict[Any, int] = {} for event in playback_events: stream_id = event["stream_id"] previous_count = event_counts_by_stream.get(stream_id, 0) event_counts_by_stream[stream_id] = previous_count + 1 return event_counts_by_streamCode Phase 2: drive the output from `streams`
Why must our second loop iterate over
streamsinstead of iterating overevent_counts_by_stream?- If a stream had zero events, its
stream_idis not inevent_counts_by_streamat all — looping overstreamsguarantees it still gets a row withevent_count = 0. - If
playback_eventscontains an orphan event whosestream_iddoes not exist instreams, looping overstreamsnaturally ignores it (just likeFROM streams LEFT JOIN playback_events). - Preserving the order of
streamsalso matches the sample tests cleanly.
def calculate_playback_counts(streams: List[Dict], playback_events: List[Dict]) -> List[Dict]: # Tally all playback events in a single O(E) pass. event_counts_by_stream = count_events_by_stream(playback_events) # Phase 2 (SQL LEFT JOIN starting from streams): iterate over `streams` rather than # `event_counts_by_stream` so streams with 0 events still appear with event_count = 0, # and events referencing unknown stream_ids are ignored. result: List[Dict] = [] for stream in streams: stream_id = stream["stream_id"] streamer_name = stream["streamer_name"] # Default to 0 when a stream had no matching rows in playback_events. event_count = event_counts_by_stream.get(stream_id, 0) result.append({ "stream_id": stream_id, "streamer_name": streamer_name, "event_count": event_count, }) return resultTracing Example 2:
streams = [(710, 'Priya'), (720, 'Quinn'), (730, 'Ravi')],playback_events = [(21, 720), (22, 720)].- After Phase 1:
event_counts_by_stream = {720: 2}. - During Phase 2:
710('Priya') ->event_counts_by_stream.get(710, 0)->0720('Quinn') ->event_counts_by_stream.get(720, 0)->2730('Ravi') ->event_counts_by_stream.get(730, 0)->0
- If a stream had zero events, its
Complete solution
from typing import Any, Dict, List, Optional, Set, Tuple def count_events_by_stream(playback_events: List[Dict]) -> Dict[Any, int]: """Phase 1 (SQL GROUP BY stream_id): count playback events per stream_id.""" # event_counts_by_stream maps stream_id -> total event count, e.g. {501: 1, 502: 3}. event_counts_by_stream: Dict[Any, int] = {} for event in playback_events: stream_id = event["stream_id"] previous_count = event_counts_by_stream.get(stream_id, 0) event_counts_by_stream[stream_id] = previous_count + 1 return event_counts_by_stream def calculate_playback_counts(streams: List[Dict], playback_events: List[Dict]) -> List[Dict]: # Tally all playback events in a single O(E) pass. event_counts_by_stream = count_events_by_stream(playback_events) # Phase 2 (SQL LEFT JOIN starting from streams): iterate over `streams` rather than # `event_counts_by_stream` so streams with 0 events still appear with event_count = 0, # and events referencing unknown stream_ids are ignored. result: List[Dict] = [] for stream in streams: stream_id = stream["stream_id"] streamer_name = stream["streamer_name"] # Default to 0 when a stream had no matching rows in playback_events. event_count = event_counts_by_stream.get(stream_id, 0) result.append({ "stream_id": stream_id, "streamer_name": streamer_name, "event_count": event_count, }) return result✅ Submit now — all tests should pass.
Intuition & how it works
Imagine managing a music festival where you have an official schedule of every stage (streams) and a big box of scanned entry tickets (playback_events), each stamped with a stream_id. If you only stack the tickets by stage and report the stacks you see, any quiet stage that had zero visitors has no ticket stack and disappears from your report! To include every scheduled stage, you first sort and count the tickets into labeled buckets by stage ID, and then walk down the official stage schedule from top to bottom — copying the bucket count when one exists, and writing 0 when the bucket is empty.
Two obvious approaches fall short here. In SQL, a plain INNER JOIN (a join that keeps only rows matching in both tables) drops every stream with zero events, and writing COUNT(*) after a LEFT JOIN counts the NULL-padded placeholder row and mistakenly reports 1 event instead of 0. In Python, scanning the entire playback_events list from scratch for every stream takes O(S * E) time for S streams and E events, which becomes far too slow when both tables grow large.
Instead, both the SQL query and the Python function combine a hash aggregation (grouping items in a dictionary / hash table in one pass) with a left join (keeping every row from the left table streams even when nothing matches on the right):
- Suppose
streams = [(710, "Priya"), (720, "Quinn")]andplayback_events = [(21, 720), (22, 720)](no events for710). - In SQL:
FROM streams AS s LEFT JOIN playback_events AS e ON e.stream_id = s.stream_idproduces one row for(710, "Priya")withevent_id = NULL, and two rows for(720, "Quinn")withevent_idvalues21and22. Grouping by(s.stream_id, s.streamer_name)and calling the aggregate functionCOUNT(e.event_id)(which summarizes a group of rows while ignoringNULLvalues) yields0for Priya and2for Quinn. - In Python: Pass 1 scans
playback_eventsonce to buildevent_counts_by_stream = {720: 2}. Pass 2 loops overstreams:710is missing from the dictionary so.get(710, 0)returns0, while720looks up2.
Complexity
- Time:
O(S + E)on average, whereSis the number of rows instreamsandEis the number of rows inplayback_events. Pass 1 scans theEevents once doingO(1)average-time dictionary lookups and updates, and Pass 2 scans theSstreams once doingO(1)average-time dictionary lookups. - Space:
O(S + D), whereD <= Eis the number of distinctstream_idvalues present inplayback_events. Theevent_counts_by_streamdictionary storesDkey-value pairs, and the returnedresultlist storesSthree-field dictionaries.
In a SQL database without pre-sorted indexes, the query optimizer achieves the same O(S + E) scaling using a hash aggregate and hash join.
Edge cases
- Streams with zero events: must still appear in the output with
event_count = 0rather than being dropped or counted as1. - Empty
playback_eventstable: every stream instreamsis returned withevent_count = 0. - Empty
streamstable: returns[]even ifplayback_eventscontains rows, because the left table of theLEFT JOINis empty. - Orphan events (unknown
stream_id): events whosestream_iddoes not appear instreamsmust not create extra output rows without astreamer_name. - Multiple streams by the same streamer: if
'Nora'hostsstream_id = 1andstream_id = 2, they stay two separate rows becausestream_idis the primary key (unique row identifier) ofstreams, notstreamer_name.
Common mistakes
- Using
JOIN(INNER JOIN) instead ofLEFT JOIN: removes every stream that has zero matching rows inplayback_events. - Writing
COUNT(*)instead ofCOUNT(e.event_id)afterLEFT JOIN: a stream with zero events still produces one row in the joined table (withe.event_id = NULL), soCOUNT(*)returns1instead of0. - Filtering right-table columns in
WHERE: adding a filter such asWHERE e.event_type = 'play'discards rows wheree.event_typeisNULL, silently turning yourLEFT JOINback into anINNER JOIN. Filters on optional right-table columns belong inside theONclause (LEFT JOIN playback_events AS e ON e.stream_id = s.stream_id AND e.event_type = 'play'). - Grouping only by
streamer_name: collapses multiple streams created by the same streamer into a single combined count. - Iterating over
event_counts_by_streamin Python to build the output: skips zero-event streams completely and emits broken rows for unknownstream_ids.
Alternative approaches
- Pre-aggregate
playback_eventsbefore joining (SQL subquery / CTE): notice that our Python code actually aggregatesplayback_eventsbefore joining tostreams! Doing the exact same thing in SQL shrinksplayback_eventsdown to at most one row perstream_idbefore the join runs, usingCOALESCE(c.event_count, 0)(COALESCEreturns its first non-NULLargument) to turn unmatchedNULLs into0:
SELECT
s.stream_id,
s.streamer_name,
COALESCE(c.event_count, 0) AS event_count
FROM streams AS s
LEFT JOIN (
SELECT stream_id, COUNT(*) AS event_count
FROM playback_events
GROUP BY stream_id
) AS c
ON c.stream_id = s.stream_id;
Follow-up questions
- How would you adjust the SQL query so that only streams exceeding 100 playback events are returned? Add
HAVING COUNT(e.event_id) > 100right after theGROUP BYclause. In SQL,WHEREfilters individual rows before grouping, whereasHAVINGfilters whole groups after an aggregate likeCOUNT(...)has been computed. Because any stream with more than 100 events has at least 1 event, you can also replaceLEFT JOINwithINNER JOIN(JOIN), allowing the engine to ignore zero-event streams immediately. - How could you structure a CTE or subquery to compute the mean playback count per creator? A CTE (Common Table Expression) is a named temporary result defined with
WITH name AS (...)at the top of a query so multi-step aggregations stay easy to read. First clarify whether the interviewer wants each creator's average events per stream (one row per creator) or a single platform-wide average of total events per creator: for each creator's per-stream average, put our mainLEFT JOINquery insideWITH per_stream AS (...)so zero-event streams still count as0, then runSELECT streamer_name, AVG(event_count * 1.0) AS avg_events_per_stream FROM per_stream GROUP BY streamer_name(multiplying by1.0prevents integer-division truncation in dialects like SQL Server). If instead they want one overall average of total events per creator, group the CTE bystreamer_name(COUNT(e.event_id) AS total_events) and takeSELECT AVG(total_events * 1.0) FROM per_streamer. - How would indexing stream_id on both tables affect read speed, storage, and write throughput? A database index (typically a sorted B-tree lookup structure) speeds up finding or ordering rows by key at the cost of extra disk space and extra work on writes. Because
stream_idis already the primary key ofstreams, the database automatically maintains a unique index onstreams.stream_id, so adding a duplicate index there wastes space and slows inserts for zero query gain. Adding an index on the foreign keyplayback_events.stream_id, however, is very helpful whenever queries filter to a subset of streams, enables an index-only scan (counting matchingstream_identries straight from the compact index without reading full event rows), and provides pre-sorted order for a streaming group-by/merge join — though on a high-throughput event table, everyINSERTintoplayback_eventswill pay a small overhead to update that index.
Follow-up questions
- How would you adjust the SQL query so that only streams exceeding 100 playback events are returned?
- How could you structure a CTE or subquery to compute the mean playback count per creator?
- How would indexing stream_id on both tables affect read speed, storage, and write throughput?
Similar questions
- Score Margin in an Even-Flip Array Game
- Dynamic Dynasty Succession Without an Initial Monarch
- DOM Button Click Listener and Event Target
- Catalog Search, Filtering, and Pagination
- Case-Insensitive Ticket Queue Filtering and UI State Debugging
- Library Hold-Queue and Loan Reminder Notification Manager