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:

  1. streams
    • stream_id (INTEGER): primary key uniquely identifying each broadcast session.
    • streamer_name (VARCHAR): handle or display name of the creator running that session.
  2. playback_events
    • event_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 streams must appear in the output, showing event_count = 0 whenever a session has zero matching play logs.
  • Play logs whose stream_id does not match any row in streams are 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, and stream_id values in streams are distinct integers.
  • 0 <= len(playback_events) <= 10^5, and event_id values in playback_events are distinct integers.
  • Multiple rows in streams may share the same streamer_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

  1. Restate the problem

    We have two relational tables from a live-video analytics pipeline:

    • streams: one row per broadcast session, with stream_id (the unique identifier, or primary key, of each session) and streamer_name.
    • playback_events: one row per play log entry, with event_id (unique per event) and stream_id (recording which session was played).

    We need one summary row for every session in streams containing stream_id, streamer_name, and event_count (how many play events referenced that session). When a session has zero play events, it must still appear in the output with event_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}, ...]
    
  2. Why INNER JOIN and COUNT(*) fail on zero-event streams

    Suppose streams has Priya (710), Quinn (720), and Ravi (730), while playback_events has two plays on session 720 and none at all on 710 or 730 (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 JOIN table above:

    1. Start from streams and LEFT 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 with NULL.
    2. Use COUNT(e.event_id), never COUNT(*): in SQL, COUNT(*) counts rows (including rows padded with NULLs), so COUNT(*) would report 1 play for Priya and 1 play for Ravi! By contrast, COUNT(column) counts only non-NULL values in that column, so COUNT(e.event_id) skips NULL and accurately returns 0 for Priya and Ravi.
  3. Write the SQL query

    Finally, we group the joined rows by s.stream_id and s.streamer_name:

    • Grouping by s.stream_id ensures that if Nora hosted two separate sessions (say stream_id = 1 and stream_id = 2), each session keeps its own row instead of merging together under 'Nora'.
    • Including s.streamer_name alongside s.stream_id in GROUP BY satisfies standard SQL's rule that every non-aggregated SELECT column must appear in GROUP BY (since stream_id uniquely determines streamer_name, adding streamer_name never 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;
    
  4. From SQL to Python: avoid O(S * E) nested loops

    In Python, the brute-force way to compute event_count is: for each of the S streams, loop through all E playback events and count how many share the same stream_id. That works on tiny inputs, but it performs S * E comparisons — with 100,000 streams and 1,000,000 events, that is 100,000,000,000 iterations.

    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)
    
    1. Phase 1 (GROUP BY stream_id): scan playback_events once and tally counts in a dictionary event_counts_by_stream in O(E) time.
    2. Phase 2 (LEFT JOIN from streams): scan streams once and look up each stream_id in event_counts_by_stream (defaulting to 0 if absent) in O(S) time.
  5. Code Phase 1: tally playback events in one pass

    Each event dictionary has "stream_id". Using event_counts_by_stream.get(stream_id, 0) returns 0 the first time we see a stream_id and 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_stream
    
  6. Code Phase 2: drive the output from `streams`

    Why must our second loop iterate over streams instead of iterating over event_counts_by_stream?

    • If a stream had zero events, its stream_id is not in event_counts_by_stream at all — looping over streams guarantees it still gets a row with event_count = 0.
    • If playback_events contains an orphan event whose stream_id does not exist in streams, looping over streams naturally ignores it (just like FROM streams LEFT JOIN playback_events).
    • Preserving the order of streams also 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 result
    

    Tracing 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) -> 0
      • 720 ('Quinn') -> event_counts_by_stream.get(720, 0) -> 2
      • 730 ('Ravi') -> event_counts_by_stream.get(730, 0) -> 0
  7. 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")] and playback_events = [(21, 720), (22, 720)] (no events for 710).
  • In SQL: FROM streams AS s LEFT JOIN playback_events AS e ON e.stream_id = s.stream_id produces one row for (710, "Priya") with event_id = NULL, and two rows for (720, "Quinn") with event_id values 21 and 22. Grouping by (s.stream_id, s.streamer_name) and calling the aggregate function COUNT(e.event_id) (which summarizes a group of rows while ignoring NULL values) yields 0 for Priya and 2 for Quinn.
  • In Python: Pass 1 scans playback_events once to build event_counts_by_stream = {720: 2}. Pass 2 loops over streams: 710 is missing from the dictionary so .get(710, 0) returns 0, while 720 looks up 2.

Complexity

  • Time: O(S + E) on average, where S is the number of rows in streams and E is the number of rows in playback_events. Pass 1 scans the E events once doing O(1) average-time dictionary lookups and updates, and Pass 2 scans the S streams once doing O(1) average-time dictionary lookups.
  • Space: O(S + D), where D <= E is the number of distinct stream_id values present in playback_events. The event_counts_by_stream dictionary stores D key-value pairs, and the returned result list stores S three-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 = 0 rather than being dropped or counted as 1.
  • Empty playback_events table: every stream in streams is returned with event_count = 0.
  • Empty streams table: returns [] even if playback_events contains rows, because the left table of the LEFT JOIN is empty.
  • Orphan events (unknown stream_id): events whose stream_id does not appear in streams must not create extra output rows without a streamer_name.
  • Multiple streams by the same streamer: if 'Nora' hosts stream_id = 1 and stream_id = 2, they stay two separate rows because stream_id is the primary key (unique row identifier) of streams, not streamer_name.

Common mistakes

  • Using JOIN (INNER JOIN) instead of LEFT JOIN: removes every stream that has zero matching rows in playback_events.
  • Writing COUNT(*) instead of COUNT(e.event_id) after LEFT JOIN: a stream with zero events still produces one row in the joined table (with e.event_id = NULL), so COUNT(*) returns 1 instead of 0.
  • Filtering right-table columns in WHERE: adding a filter such as WHERE e.event_type = 'play' discards rows where e.event_type is NULL, silently turning your LEFT JOIN back into an INNER JOIN. Filters on optional right-table columns belong inside the ON clause (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_stream in Python to build the output: skips zero-event streams completely and emits broken rows for unknown stream_ids.

Alternative approaches

  • Pre-aggregate playback_events before joining (SQL subquery / CTE): notice that our Python code actually aggregates playback_events before joining to streams! Doing the exact same thing in SQL shrinks playback_events down to at most one row per stream_id before the join runs, using COALESCE(c.event_count, 0) (COALESCE returns its first non-NULL argument) to turn unmatched NULLs into 0:
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) > 100 right after the GROUP BY clause. In SQL, WHERE filters individual rows before grouping, whereas HAVING filters whole groups after an aggregate like COUNT(...) has been computed. Because any stream with more than 100 events has at least 1 event, you can also replace LEFT JOIN with INNER 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 main LEFT JOIN query inside WITH per_stream AS (...) so zero-event streams still count as 0, then run SELECT streamer_name, AVG(event_count * 1.0) AS avg_events_per_stream FROM per_stream GROUP BY streamer_name (multiplying by 1.0 prevents integer-division truncation in dialects like SQL Server). If instead they want one overall average of total events per creator, group the CTE by streamer_name (COUNT(e.event_id) AS total_events) and take SELECT 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_id is already the primary key of streams, the database automatically maintains a unique index on streams.stream_id, so adding a duplicate index there wastes space and slows inserts for zero query gain. Adding an index on the foreign key playback_events.stream_id, however, is very helpful whenever queries filter to a subset of streams, enables an index-only scan (counting matching stream_id entries 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, every INSERT into playback_events will pay a small overhead to update that index.

Follow-up questions

Similar questions

More Adia interview questions

All 2 Adia questions →