Daily and Cumulative Player Sessions With Date Gap Filling
Medium · Data Manipulation (SQL/Python) · Data Scientist · Technical Screen
Problem Statement
You are analyzing player activity logs from a table game_sessions(session_id INT PRIMARY KEY, player_id INT, game_id INT, session_date DATE), optionally paired with a reference date table calendar(d DATE). Every record in game_sessions represents one completed session (even when the same player launches the same game_id multiple times on the same date).
Design both the SQL queries and the equivalent Python implementation:
def compute_daily_cumulative_games(rows: List[List], calendar: List[str]) -> Dict[str, List[List]]:
You need to produce per-player daily and running session totals [player_id, session_date, daily_games, cum_games] under two specifications:
- Part A (
"part_a"— active dates only): Emit one row per(player_id, session_date)on which that player logged at least one session.daily_gamesis the number of sessions recorded by that player onsession_date, andcum_gamesis the running total of sessions played by that player from their earliest session throughsession_dateinclusive. In SQL, computecum_gameswith window functions and no user-defined functions. - Part B (
"part_b"— gap-filled within each player's active span): Emit all rows from Part A plus any inactive datedfromcalendarsatisfyingfirst_session_date <= d <= last_session_datefor that player. On those zero-activity gap dates,daily_gamesis0andcum_gamescarries forward the player's running total from their latest prior active date. Dates strictly earlier than a player's first session or strictly later than their last session are never added. In SQL, build this date grid usingcalendar(d)without recursive CTEs.
In Python:
- Each element of rows is [session_id, player_id, game_id, session_date], where session_id, player_id, and game_id are integers and session_date is an ISO-8601 string "YYYY-MM-DD".
- calendar is a list of "YYYY-MM-DD" strings (not necessarily sorted or deduplicated). Any active session_date present in rows must still be retained in "part_b" even if calendar omits it.
- Return {"part_a": [...], "part_b": [...]} with rows in both lists ordered by player_id ascending (numeric order), then session_date ascending (chronological order).
Examples
Example 1
Input:
rows = [
[10, 201, 50, "2026-03-30"],
[11, 201, 55, "2026-03-30"],
[12, 205, 50, "2026-03-31"],
[13, 201, 50, "2026-04-01"],
[14, 205, 60, "2026-04-02"],
[15, 205, 60, "2026-04-02"]
]
calendar = [
"2026-03-29", "2026-03-30", "2026-03-31",
"2026-04-01", "2026-04-02", "2026-04-03"
]
Output:
{
"part_a": [
[201, "2026-03-30", 2, 2],
[201, "2026-04-01", 1, 3],
[205, "2026-03-31", 1, 1],
[205, "2026-04-02", 2, 3]
],
"part_b": [
[201, "2026-03-30", 2, 2],
[201, "2026-03-31", 0, 2],
[201, "2026-04-01", 1, 3],
[205, "2026-03-31", 1, 1],
[205, "2026-04-01", 0, 1],
[205, "2026-04-02", 2, 3]
]
}
Player 201 plays twice on 2026-03-30 and once on 2026-04-01, so Part B inserts only the interior gap day 2026-03-31 (daily_games = 0, cum_games = 2) and ignores 2026-03-29, 2026-04-02, and 2026-04-03. Player 205 plays once on 2026-03-31 and twice on 2026-04-02 (both on game_id = 60), so Part B inserts 2026-04-01 (daily_games = 0, cum_games = 1) while ignoring dates outside [2026-03-31, 2026-04-02].
Example 2
Input:
rows = [
[1, 30, 8, "2026-06-10"],
[2, 12, 4, "2026-06-08"],
[3, 12, 9, "2026-06-09"]
]
calendar = ["2026-06-07", "2026-06-08", "2026-06-09", "2026-06-10", "2026-06-11"]
Output:
{
"part_a": [
[12, "2026-06-08", 1, 1],
[12, "2026-06-09", 1, 2],
[30, "2026-06-10", 1, 1]
],
"part_b": [
[12, "2026-06-08", 1, 1],
[12, "2026-06-09", 1, 2],
[30, "2026-06-10", 1, 1]
]
}
Player 12 sorts ahead of player 30 numerically, has consecutive active days with no missing interior date, and player 30 has only one active day (first_date == last_date), so "part_a" and "part_b" are identical.
Constraints
0 <= len(rows) <= 10^50 <= len(calendar) <= 3660- Each row has 4 elements
[session_id, player_id, game_id, session_date]with integer IDs and valid"YYYY-MM-DD"date strings. - If
rowsis empty, both"part_a"and"part_b"must be[].
Step-by-step walkthrough
Understand Part A and Part B
Each row in
game_sessionsrecords one session played:[session_id, player_id, game_id, session_date], and every session row counts as 1 game played (even if a player plays the samegame_idtwice on the same day).We need to produce
[player_id, session_date, daily_games, cum_games]rows in two forms: - Part A (active days only): one row per player for each date that player actually played, showing that day's session count (daily_games) and the player's running total up to and including that date (cum_games). - Part B (gap-filled between first and last session): the same columns, except any missing calendar day strictly between a player's first active date and last active date is filled in withdaily_games = 0and the previouscum_gamescarried forward. Dates before a player's first session or after their last session are not added.Example 1 for player 201 (sessions on 03-30 x2, 04-01 x1): Part A (active days only) Part B (03-30 .. 04-01 padded from calendar) player | date | daily | cum player | date | daily | cum -------+------------+-------+---- -------+------------+-------+---- 201 | 2026-03-30 | 2 | 2 201 | 2026-03-30 | 2 | 2 201 | 2026-04-01 | 1 | 3 201 | 2026-03-31 | 0 | 2 <-- gap day filled! 201 | 2026-04-01 | 1 | 3Why recounting is slow — and why windowing raw rows fails
A naive calculation scans the whole table for every
(player_id, session_date)output row to recount how many sessions occurred on or before that date. In SQL that is a correlated subquery; in Python it is nested loops takingO(n^2)time.There is also a classic SQL trap when switching to window functions: applying
COUNT(*) OVER (PARTITION BY player_id ORDER BY session_date)directly to the rawgame_sessionsrows without grouping first! Look at what happens to player201's two sessions on2026-03-30:Raw rows for player 201 on 2026-03-30: session 10 (2026-03-30) -> produces duplicate date row #1! session 11 (2026-03-30) -> produces duplicate date row #2!Instead of one summary row
[201, '2026-03-30', 2, 2], windowing raw rows emits two output rows for2026-03-30. Worse, SQL's defaultRANGEframe gives both rowscum_games = 2, while aROWSframe gives1and2— and neither collapses the day!The clean rule is always aggregate to one row per
(player_id, session_date)first, then take the cumulative window sum.Write Part A in SQL: `GROUP BY` day, then window `SUM`
We structure Part A in two clean stages using a CTE (Common Table Expression — a named temporary result introduced with
WITH):dailygroupsgame_sessionsby(player_id, session_date)so each player has at most one row per calendar day, holdingCOUNT(*) AS daily_games.- The outer
SELECTapplies a window function (SUM(daily_games) OVER (...)— an aggregate computed across related rows without collapsing them):PARTITION BY player_idrestarts the running total at0for each player.ORDER BY session_datewalks that player's active days chronologically.ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROWsums from the player's very first row through the current row.
-- Step 1: Collapse raw sessions into one count per (player, active date) WITH daily AS ( SELECT player_id, session_date, COUNT(*) AS daily_games FROM game_sessions GROUP BY player_id, session_date ) -- Step 2: Sum daily counts chronologically within each player partition SELECT player_id, session_date, daily_games, SUM(daily_games) OVER ( PARTITION BY player_id ORDER BY session_date ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW ) AS cum_games FROM daily ORDER BY player_id, session_date;Write Part B in SQL: build a per-player date grid without recursion
To include zero-activity days between a player's first and last session (without recursive CTEs), we build a date spine (the complete grid of
(player_id, session_date)rows that should appear in the output) before summing:bounds: findMIN(session_date) AS first_dateandMAX(session_date) AS last_dateper player fromdaily.grid: joinboundstocalendaronc.d BETWEEN b.first_date AND b.last_date. AddingUNION SELECT player_id, session_date FROM dailyboth deduplicates any repeated dates incalendarand safeguards active session days even ifcalendarhad a gap.LEFT JOINdailyontogrid: rest days have no match indaily, sod.daily_gamesisNULL. Wrapping it inCOALESCE(d.daily_games, 0)turnsNULLinto0both indaily_gamesand inside the windowSUM.
-- Step 1: Count games per player on each active date WITH daily AS ( SELECT player_id, session_date, COUNT(*) AS daily_games FROM game_sessions GROUP BY player_id, session_date ), -- Step 2: Find each player's first and last active session date bounds AS ( SELECT player_id, MIN(session_date) AS first_date, MAX(session_date) AS last_date FROM daily GROUP BY player_id ), -- Step 3: Build every (player, date) pair inside that player's active span grid AS ( SELECT b.player_id, c.d AS session_date FROM bounds b JOIN calendar c ON c.d BETWEEN b.first_date AND b.last_date UNION SELECT player_id, session_date FROM daily ) -- Step 4: Left join daily counts (0 on rest days) and take a running sum SELECT g.player_id, g.session_date, COALESCE(d.daily_games, 0) AS daily_games, SUM(COALESCE(d.daily_games, 0)) OVER ( PARTITION BY g.player_id ORDER BY g.session_date ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW ) AS cum_games FROM grid g LEFT JOIN daily d ON d.player_id = g.player_id AND d.session_date = g.session_date ORDER BY g.player_id, g.session_date;Count per-player daily sessions in Python
Now let's mirror the exact same pipeline in Python for the automated judge
compute_daily_cumulative_games(rows, calendar), which returns{"part_a": [...], "part_b": [...]}.First,
count_daily_gamesimplements thedailyCTE using a nested dictionary{player_id: {session_date: count}}.from typing import Dict, List def count_daily_games(rows: List[List]) -> Dict[int, Dict[str, int]]: """Group raw sessions into {player_id: {session_date: daily_game_count}}.""" # daily_counts: {201: {"2026-03-30": 2, "2026-04-01": 1}, ...} daily_counts: Dict[int, Dict[str, int]] = {} for row in rows: # Each input row is [session_id, player_id, game_id, session_date] and counts as 1 game. player_id = row[1] session_date = row[3] if player_id not in daily_counts: daily_counts[player_id] = {} per_day = daily_counts[player_id] per_day[session_date] = per_day.get(session_date, 0) + 1 return daily_countsBuild the date span and running sum in Python
Why can we compare and sort date strings like
"2026-03-31"and"2026-04-01"directly without parsingdatetimeobjects? Because ISO-8601 dates (YYYY-MM-DD) place the 4-digit year first, 2-digit zero-padded month second, and 2-digit zero-padded day third — so left-to-right string order is always identical to chronological order, even across month and year boundaries!That gives two tiny helpers that mirror
gridand the windowSUM: -dates_in_span(active_dates, calendar): starts asetfromactive_dates(theUNIONsafeguard), adds everycal_datesatisfyingfirst_date <= cal_date <= last_date, and returnssorted(span_dates). -build_running_rows(player_id, sorted_dates, per_day): walkssorted_datesin order, usesper_day.get(session_date, 0)(theCOALESCE(..., 0)equivalent), and adds it tocumulative_games. Both Part A and Part B call this exact same helper!from typing import Dict, List def dates_in_span(active_dates: List[str], calendar: List[str]) -> List[str]: """Return sorted unique dates in [first_active, last_active] from active_dates and calendar.""" first_date = active_dates[0] last_date = active_dates[-1] # Seed the set with active_dates so session days are kept even if absent from calendar. span_dates = set(active_dates) for cal_date in calendar: # Inclusive <= bounds pad zero-activity days only inside this player's active window. if first_date <= cal_date <= last_date: span_dates.add(cal_date) return sorted(span_dates) def build_running_rows( player_id: int, sorted_dates: List[str], per_day: Dict[str, int] ) -> List[List]: """Build [player_id, session_date, daily_games, cum_games] rows in chronological order.""" player_rows = [] cumulative_games = 0 for session_date in sorted_dates: # Rest days added from the calendar have 0 daily games and carry cum_games forward. daily_games = per_day.get(session_date, 0) cumulative_games += daily_games player_rows.append([player_id, session_date, daily_games, cumulative_games]) return player_rowsTrace Example 1 across both players
Let's verify both players on
calendar = ['2026-03-29', '2026-03-30', '2026-03-31', '2026-04-01', '2026-04-02', '2026-04-03']:daily_counts: 201 -> {'2026-03-30': 2, '2026-04-01': 1} 205 -> {'2026-03-31': 1, '2026-04-02': 2} Player 201: active_dates = ['2026-03-30', '2026-04-01'] (03-29, 04-02, 04-03 are outside [03-30, 04-01]!) -> Part A rows: [201, '2026-03-30', 2, 2], [201, '2026-04-01', 1, 3] padded_dates = ['2026-03-30', '2026-03-31', '2026-04-01'] -> Part B adds [201, '2026-03-31', 0, 2] between 03-30 and 04-01 Player 205: active_dates = ['2026-03-31', '2026-04-02'] (first_date is 2026-03-31, so 03-29 & 03-30 are excluded!) -> Part A rows: [205, '2026-03-31', 1, 1], [205, '2026-04-02', 2, 3] padded_dates = ['2026-03-31', '2026-04-01', '2026-04-02'] -> Part B rows: [205, '2026-03-31', 1, 1], [205, '2026-04-01', 0, 1], [205, '2026-04-02', 2, 3]Assemble the complete solution
Loop over
sorted(daily_counts)so integerplayer_ids appear in numeric order (9before10), and collect bothpart_aandpart_b.from typing import Any, Dict, List, Optional, Set, Tuple def count_daily_games(rows: List[List]) -> Dict[int, Dict[str, int]]: """Group raw sessions into {player_id: {session_date: daily_game_count}}.""" # daily_counts: {201: {"2026-03-30": 2, "2026-04-01": 1}, ...} daily_counts: Dict[int, Dict[str, int]] = {} for row in rows: # Each input row is [session_id, player_id, game_id, session_date] and counts as 1 game. player_id = row[1] session_date = row[3] if player_id not in daily_counts: daily_counts[player_id] = {} per_day = daily_counts[player_id] per_day[session_date] = per_day.get(session_date, 0) + 1 return daily_counts def dates_in_span(active_dates: List[str], calendar: List[str]) -> List[str]: """Return sorted unique dates in [first_active, last_active] from active_dates and calendar.""" first_date = active_dates[0] last_date = active_dates[-1] # Seed the set with active_dates so session days are kept even if absent from calendar. span_dates = set(active_dates) for cal_date in calendar: # Inclusive <= bounds pad zero-activity days only inside this player's active window. if first_date <= cal_date <= last_date: span_dates.add(cal_date) return sorted(span_dates) def build_running_rows( player_id: int, sorted_dates: List[str], per_day: Dict[str, int] ) -> List[List]: """Build [player_id, session_date, daily_games, cum_games] rows in chronological order.""" player_rows = [] cumulative_games = 0 for session_date in sorted_dates: # Rest days added from the calendar have 0 daily games and carry cum_games forward. daily_games = per_day.get(session_date, 0) cumulative_games += daily_games player_rows.append([player_id, session_date, daily_games, cumulative_games]) return player_rows def compute_daily_cumulative_games( rows: List[List], calendar: List[str] ) -> Dict[str, List[List]]: # Phase 1: Collapse raw sessions into per-player, per-date counts (SQL GROUP BY). daily_counts = count_daily_games(rows) part_a = [] part_b = [] # Phase 2: Sort integer player_ids numerically, then compute Part A and Part B running sums. for player_id in sorted(daily_counts): per_day = daily_counts[player_id] # ISO "YYYY-MM-DD" strings sort identically to calendar dates. active_dates = sorted(per_day) padded_dates = dates_in_span(active_dates, calendar) part_a.extend(build_running_rows(player_id, active_dates, per_day)) part_b.extend(build_running_rows(player_id, padded_dates, per_day)) return {"part_a": part_a, "part_b": part_b}✅ Submit now — all tests should pass.
Intuition & how it works
Think of tracking workouts in a paper notebook. If you go to the gym twice on Friday, once on Saturday, and once on Monday, you first tally each day onto a single line (Friday: 2, Saturday: 1, Monday: 1) and then keep a running pencil total down the margin (2, 3, 4). In SQL, that running margin total is a window function (an expression like SUM(...) OVER (...) that computes a running value across ordered rows without collapsing them into a single summary row). For Part B, where inactive gap days like Sunday must also appear, you first write down every calendar date from a player's first active day through their last active day — a date spine (a scaffold table of all required (player_id, date) pairs) — fill missing days with 0 using COALESCE (a SQL function that returns its first non-NULL argument), and run the exact same cumulative sum down the page.
Why do the two obvious shortcuts fail? Recomputing the cumulative count from scratch for every (player, date) row via a correlated subquery (a subquery that re-executes once per outer row) rescans historical rows repeatedly in O(n^2) time. On the other hand, putting a window function directly on raw ungrouped game_sessions rows fails whenever a player has multiple sessions on the same day, because it outputs duplicate rows for that date instead of one daily row.
Here is a mini walkthrough for player 201 in Example 1 (two sessions on 03-30, none on 03-31, and one on 04-01):
1. Group by (player_id, session_date):
(201, 03-30) -> daily = 2
(201, 04-01) -> daily = 1
2. Part A running sum over active dates:
03-30: daily=2, cum=2 | 04-01: daily=1, cum=3
3. Part B pad calendar dates in [03-30, 04-01] first, then running sum:
03-30: daily=2, cum=2 | 03-31: daily=0, cum=2 | 04-01: daily=1, cum=3
Complexity
Let n be the number of session rows, P be the number of distinct players (P <= n), and C be the number of dates in calendar.
- Python Time:
O(n + P * C + S log S), whereS <= n + P * Cis the total number of(player, date)output rows across all players. We scan theninput rows once inO(n)to populatedaily_counts, scan theCcalendar dates once per player (O(P * C)) to collect in-span dates, and sort each player's unique dates before doing one linear running-sum pass. - Python Space:
O(n + P * C).daily_countsstores at mostn(player, date)entries, and thepart_aandpart_boutput tables hold at mostnandn + P * Crows respectively. - SQL Query Scaling & Indexes: Grouping and windowing by
(player_id, session_date)requires sorting thenrows inO(n log n)time unless a composite B-tree index exists ongame_sessions(player_id, session_date), which lets the database stream rows already in partition-and-date order. For Part B, an index oncalendar(d)letsc.d BETWEEN b.first_date AND b.last_dateperform a fast index range scan per player instead of scanning the entire calendar table.
Edge cases
- Empty
game_sessions(rows = []):daily_countsis empty, so bothpart_aandpart_breturn[]even whencalendaris non-empty. - Player active on only a single day:
first_date == last_date, so no gap days exist inside[first_date, last_date]and Part B produces the exact same single row as Part A. - Multiple sessions on the same day (same or different
game_id): Every row counts as one game, collapsing into a single row for that date withdaily_gamesequal to the session count. - Zero-padding strictly within each player's own span: In Example 1, player
205is active from2026-03-31through2026-04-02, so2026-03-29,2026-03-30, and2026-04-03are not added for player205even though they appear incalendar. - Unsorted inputs, duplicate calendar entries, and numeric
player_idorder: Using asetremoves duplicate calendar dates, sortingdaily_countsorders integer IDs numerically (9before10), and ISO"YYYY-MM-DD"strings sort chronologically across month and year rollovers. - Active session date missing from
calendar: Seedingspan_dates(andUNIONin SQL) withactive_datespreserves every real session day socum_gamesnever loses games.
Common mistakes
- Applying the window function before
GROUP BY: Windowing rawgame_sessionsemits multiple rows on days with more than one session. Always aggregate per(player_id, session_date)first (either in adailyCTE or by writingSUM(COUNT(*)) OVER (...)in the sameGROUP BYquery). - Cross-joining all players with the entire
calendartable:players CROSS JOIN calendarpads0-game rows before a player's first session and after their last session, violating Part B's rule. Restrict the join toc.d BETWEEN b.first_date AND b.last_date. - Using
INNER JOINinstead ofLEFT JOIN(or filteringdinWHERE): Joininggridtodailywith anINNER JOIN— or adding aWHERE d.player_id IS NOT NULLfilter — throws away all the zero-activity calendar dates you just generated. - Writing
COUNT(d.daily_games)instead ofSUM(COALESCE(d.daily_games, 0))on the grid:COUNTcounts how many active days occurred (1per active day), ignoring days where a player played2or more games! - Forgetting
COALESCE(..., 0)ondaily_games: SQLSUMignoresNULLs socum_gameswould still advance properly, but thedaily_gamescolumn itself would outputNULLinstead of0on rest days. - Sorting non-ISO date strings lexicographically:
"2026-03-31" < "2026-04-01"works because ISO-8601 isYYYY-MM-DD; strings formatted like"3/31/2026"or"2026-3-9"must be parsed asDATEobjects first.
Alternative approaches
- Single-block SQL for Part A (no CTE): Because SQL evaluates
GROUP BYaggregates before window functions in theSELECTlist, Part A can be written in one block asSELECT player_id, session_date, COUNT(*) AS daily_games, SUM(COUNT(*)) OVER (PARTITION BY player_id ORDER BY session_date ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS cum_games FROM game_sessions GROUP BY player_id, session_date;. Using adailyCTE is usually easier to read and extends directly to Part B. - Date generation without a
calendartable (when allowed): In PostgreSQL or DuckDB,generate_series(first_date, last_date, INTERVAL '1 day')generates each player's date spine on the fly without needing a separatecalendartable or a recursive CTE.
Follow-up questions
- How would you adapt the SQL window query to compute a trailing 7-calendar-day session total instead of a lifetime running sum? On Part B's gap-filled grid (where every calendar date has one row per player), change the window frame (the subset of partition rows summed at each step) to
ROWS BETWEEN 6 PRECEDING AND CURRENT ROW, covering today plus the 6 prior calendar days. On Part A's unpadded table,6 PRECEDINGrows would wrongly reach back 6 active days that might be weeks apart, so you would instead need a value-basedRANGEframe such asORDER BY julianday(session_date) RANGE BETWEEN 6 PRECEDING AND CURRENT ROWin SQLite (orORDER BY session_date RANGE BETWEEN INTERVAL '6 days' PRECEDING AND CURRENT ROWin PostgreSQL). - Suppose cum_games had to count cumulative unique game_ids a player has ever tried up to each date rather than total sessions. Why does summing daily distinct counts fail, and how would you write it in SQL? Summing daily
COUNT(DISTINCT game_id)double-counts any game replayed on multiple dates, and most SQL engines disallowCOUNT(DISTINCT game_id) OVER (ORDER BY ...). Instead, first find the debut date of every(player_id, game_id)pair withSELECT player_id, game_id, MIN(session_date) AS debut_date FROM game_sessions GROUP BY player_id, game_id, group by(player_id, debut_date)to count how many brand-new titles each player unlocked per day, and apply the cumulative windowSUMover those daily new-game counts. - If game_sessions ingested hundreds of millions of rows per day, how would you redesign this computation as an incremental daily pipeline? Maintain a date-partitioned summary table keyed by
(player_id, session_date, daily_games, cum_games)plus a lightweight per-player state table(player_id, first_date, last_date, latest_cum_games)instead of rescanning historical logs. Each nightly job aggregates only yesterday's raw events into(player_id, yesterday_games)and merges them with the state table (new_cum = prev_cum + yesterday_games, while emitting0-session rows for any gap days betweenlast_dateand yesterday when a returning player logs back in), cutting daily compute from full-historyO(N log N)to single-dayO(D).
Follow-up questions
- How would you adapt the SQL window query to compute a trailing 7-calendar-day session total instead of a lifetime running sum?
- Suppose cum_games had to count cumulative unique game_ids a player has ever tried up to each date rather than total sessions. Why does summing daily distinct counts fail, and how would you write it in SQL?
- If game_sessions ingested hundreds of millions of rows per day, how would you redesign this computation as an incremental daily pipeline?
Similar questions
- Job Posting Engagement Metrics Excluding Non-Viewing Applicants
- Compute 7-Day DAU, D1 Retention, and Revenue Cohorts
- Class-Level 2024 Exam Summary with Zero-Filled Averages
- Summarizing Imaging Claims Spend and Fiscal Months
- Build Rolling User Features for Experiment Regression
- Week-over-Week Net Order Revenue Change