Premium Viewing Hours Rolled Up by Week and Month
SQL & DataAuto-graded · 16 test casesLast updated
Filter viewing events to premium subscribers, bucket them into Monday-start weeks and calendar months per user, sum minutes into hours, and return a sorted long-format result.
A streaming service logs every viewing session as a record. You are given a list of these records and need to report how much time premium subscribers spend watching, summarised per user by week and by calendar month.
Implement a function that receives rows, a list of dictionaries. Each dictionary has these keys:
user_id(int): the viewer.video_id(str): the video watched (not needed for the result).watched_minutes(int): minutes watched in this session.watched_at(str): timestamp of the session in ISO 8601 form.subscription(str): the viewer's plan for this session.
Task
- Keep only rows whose
subscriptionis exactly"premium"(case-sensitive). Filtering is per row, not per user. - For each kept row, add its
watched_minutesto two buckets for that user:- a month bucket keyed by the calendar month of the timestamp, formatted
YYYY-MM; - a week bucket keyed by the date of the Monday that starts the week containing the timestamp, formatted
YYYY-MM-DD. Weeks run Monday through Sunday, so a Sunday belongs to the week that began the previous Monday.
- a month bucket keyed by the calendar month of the timestamp, formatted
- Convert each bucket's total minutes to hours by dividing by 60 (as a floating-point number, with no rounding).
- Return one dictionary per non-empty bucket with these keys:
user_idperiod_type: the string"week"or"month"period: the bucket key described abovewatched_hours: total minutes divided by 60
Details
- The date is read from the timestamp exactly as written; do not convert between time zones. A timestamp may use a space or
Tbetween date and time, and may end inZor include an explicit UTC offset. - A week may straddle two months. It is still one week bucket, while its events are split across the two month buckets.
- Weeks are identified by their Monday date, not by week number, so year boundaries need no special handling.
- Users with no premium rows do not appear in the output. If there are no premium rows at all, return an empty list.
- Sort the result by
user_idascending, then byperiod_typeas a string (so"month"comes before"week"), then byperiodas a string ascending.
Constraints
0 <= len(rows) <= 10^5watched_minutesis a non-negative integer.watched_atis a valid ISO 8601 timestamp.subscriptioncan be any string; only the exact value"premium"counts.
Examples
Example 1
Input: premium_hours_by_period([{'user_id': 101, 'video_id': 'v89', 'watched_minutes': 30, 'watched_at': '2023-04-03 10:22:05', 'subscription': 'premium'}, {'user_id': 102, 'video_id': 'v12', 'watched_minutes': 12, 'watched_at': '2023-04-04 08:10:00', 'subscription': 'free'}, {'user_id': 101, 'video_id': 'v77', 'watched_minutes': 55, 'watched_at': '2023-04-09 14:18:20', 'subscription': 'premium'}, {'user_id': 103, 'video_id': 'v51', 'watched_minutes': 20, 'watched_at': '2023-04-11 20:00:00', 'subscription': 'premium'}, {'user_id': 102, 'video_id': 'v23', 'watched_minutes': 42, 'watched_at': '2023-05-01 09:00:12', 'subscription': 'free'}])
Output: [{'user_id': 101, 'period_type': 'month', 'period': '2023-04', 'watched_hours': 1.4166666666666667}, {'user_id': 101, 'period_type': 'week', 'period': '2023-04-03', 'watched_hours': 1.4166666666666667}, {'user_id': 103, 'period_type': 'month', 'period': '2023-04', 'watched_hours': 0.3333333333333333}, {'user_id': 103, 'period_type': 'week', 'period': '2023-04-10', 'watched_hours': 0.3333333333333333}]
Example 2
Input: premium_hours_by_period([{'user_id': 1, 'video_id': 'a', 'watched_minutes': 60, 'watched_at': '2024-01-01 00:00:00', 'subscription': 'premium'}, {'user_id': 1, 'video_id': 'b', 'watched_minutes': 30, 'watched_at': '2024-01-31 23:59:59', 'subscription': 'premium'}, {'user_id': 1, 'video_id': 'c', 'watched_minutes': 90, 'watched_at': '2024-02-01 00:00:00', 'subscription': 'premium'}])
Output: [{'user_id': 1, 'period_type': 'month', 'period': '2024-01', 'watched_hours': 1.5}, {'user_id': 1, 'period_type': 'month', 'period': '2024-02', 'watched_hours': 1.5}, {'user_id': 1, 'period_type': 'week', 'period': '2024-01-01', 'watched_hours': 1}, {'user_id': 1, 'period_type': 'week', 'period': '2024-01-29', 'watched_hours': 2}]
Example 3
Input: premium_hours_by_period([{'user_id': 7, 'video_id': 'x', 'watched_minutes': 15, 'watched_at': '2023-07-15T12:00:00', 'subscription': 'free'}])
Output: []
Hints
Hint 1
Each premium row contributes to exactly two buckets: one month bucket and one week bucket. A dictionary keyed by (user_id, period_type, period) lets you accumulate minutes for both in one pass.
Hint 2
To find the week bucket, take the date part of the timestamp and subtract its weekday index (Monday = 0 ... Sunday = 6) in days. That gives the Monday of the week, and it is safe across month and year boundaries.
Hint 3
Divide by 60.0 to avoid integer truncation, and sort at the end on (user_id, period_type, period). Remember that `Z` suffixes may need rewriting to `+00:00` for older versions of `datetime.fromisoformat`.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This is a filter, bucket, and sum problem.
- Skip every row whose subscription is not exactly
"premium". - Parse the timestamp. If it ends in
Z, replace that with+00:00sodatetime.fromisoformataccepts it on older Python versions. No time zone conversion is performed, so the calendar date is the one written in the string. - Compute two keys for the event:
- the month key
YYYY-MM; - the week key, which is the date of that week's Monday (
date - weekday()days), formattedYYYY-MM-DD.
- the month key
- Add the event's minutes to
totals[(user_id, "month", month)]andtotals[(user_id, "week", week_start)]. - Convert every total to hours with
minutes / 60.0, build one output dictionary per bucket, and sort by(user_id, period_type, period).
Why it is correct
- Each premium event is added exactly once to one week bucket and once to one month bucket, so both granularities are internally consistent.
- Subtracting
weekday()days maps every day from Monday to Sunday of the same week to the same Monday, so Sundays fall into the correct week. Using the Monday date as the key avoids the ambiguity of week numbers at year boundaries. - Keys include the year, so the same month or week in different years never merge.
- A week that spans two months stays a single week bucket, while its minutes are split across the two month buckets, which is the intended behavior.
- Non-premium rows are dropped per row, so a user whose plan changes only has their premium sessions counted. Users with no premium sessions produce no buckets and so no output rows.
- Dividing by
60.0keeps fractional hours instead of truncating. - The sort order puts
"month"before"week"for each user because of plain string comparison.
Complexity
- Time: O(n + k log k), where n is the number of rows and k is the number of distinct buckets. Since k <= 2n, this is O(n log n) in the worst case.
- Space: O(k) for the totals and the output list.
Reference solution
from collections import defaultdict
from datetime import datetime, timedelta
from typing import Dict, List
def premium_hours_by_period(rows: List[Dict]) -> List[Dict]:
totals = defaultdict(int)
for row in rows:
if row["subscription"] != "premium":
continue
timestamp = row["watched_at"]
if timestamp.endswith("Z"):
timestamp = timestamp[:-1] + "+00:00"
dt = datetime.fromisoformat(timestamp)
day = dt.date()
week_start = day - timedelta(days=day.weekday())
month = dt.strftime("%Y-%m")
user_id = row["user_id"]
totals[(user_id, "month", month)] += row["watched_minutes"]
totals[(user_id, "week", week_start.isoformat())] += row["watched_minutes"]
result = []
for (user_id, period_type, period), minutes in totals.items():
result.append({
"user_id": user_id,
"period_type": period_type,
"period": period,
"watched_hours": minutes / 60.0,
})
result.sort(key=lambda item: (
item["user_id"],
item["period_type"],
item["period"],
))
return result