Live Stream Creator Stats: Weekly, Monthly Rankings and Daily Check
SQL & DataAuto-graded · 17 test casesLast updated
Join two record lists on a composite key with missing-row defaults, then compute a filtered distinct count, a per-group top-5 ranking with tie-breaks, and an every-item condition check.
Live Stream Creator Stats
A streaming platform stores two lists of records. You must compute three metrics from them in a single function call.
Input records
live_room is a list of dictionaries, one per live stream (a "room"):
| key | type | meaning |
|---|---|---|
date | string | ISO date (YYYY-MM-DD) on which the room was live |
creator_id | integer | creator who started the room |
room_id | integer | room identifier |
country | string | country the room is attributed to (for example US, ID, UK) |
live_type | string | device used to stream (for example mobile, pc) |
The pair (date, room_id) is unique in this list.
live_room_activity is a list of dictionaries holding engagement totals for a room on a date:
| key | type | meaning |
|---|---|---|
date | string | ISO date, same as the room's date |
room_id | integer | room identifier |
watch_cnt | integer | number of viewers |
gift_recieved_cnt | integer | number of gifts received (the key is spelled exactly this way) |
The pair (date, room_id) is unique in this list too.
run_date is an ISO date string representing the day the computation is run.
Matching rooms to activity
A room is matched to its activity record using both date and room_id. If a room has no matching activity record, treat both its watch_cnt and its gift_recieved_cnt as 0. Activity records that match no room are ignored.
Metric 1: q1
Count the distinct creators who launched more than 3 rooms that satisfy all of the following:
datebetween2022-10-01and2022-10-07, inclusivecountryequalsUSlive_typeequalsmobile
Result: {"creator_count": <int>}.
Metric 2: q2
Consider only rooms whose date falls in October 2022. For each pair (country, creator), the total gifts is the sum of gift_recieved_cnt (with the default of 0 for unmatched rooms) over that creator's rooms in that country. A creator with rooms in several countries is treated separately in each country.
Within each country, rank creators by total gifts descending; ties are broken by creator_id ascending. Ranks are consecutive positions 1, 2, 3, ... (tied totals still receive different ranks). Keep only the first 5 creators of each country (fewer if the country has fewer creators).
Result: a list of dictionaries, each with keys country, creator_id, total_gifts_received, rank_in_country. Order the list by country ascending (string order), and within a country by rank ascending. If there are no October rooms, the list is empty.
Metric 3: q3
Let yesterday be the calendar day immediately before run_date. Count the creators who satisfy both:
- They launched at least 2 rooms on yesterday's date.
- Every room they launched on that date has
watch_cnt >= 500(a room with no activity record counts as 0 and therefore fails).
Result: {"qualified_creator_count": <int>}.
Return value
Return a dictionary:
{
"q1": {"creator_count": ...},
"q2": [ {...}, ... ],
"q3": {"qualified_creator_count": ...}
}
Constraints
- Dates are valid ISO strings, so string comparison matches chronological order.
- Both input lists may be empty.
(date, room_id)is unique within each list.- "More than 3" means 4 or more; "at least 2" means 2 or more; the viewer threshold is inclusive (500 passes).
- Rooms outside the date, country or device filters of a metric must not contribute to that metric.
Examples
Example 1
Input: creator_live_stats([{'date': '2022-10-01', 'creator_id': 1, 'room_id': 101, 'country': 'US', 'live_type': 'mobile'}, {'date': '2022-10-02', 'creator_id': 1, 'room_id': 102, 'country': 'US', 'live_type': 'mobile'}, {'date': '2022-10-03', 'creator_id': 1, 'room_id': 103, 'country': 'US', 'live_type': 'mobile'}, {'date': '2022-10-04', 'creator_id': 1, 'room_id': 104, 'country': 'US', 'live_type': 'mobile'}, {'date': '2022-10-05', 'creator_id': 2, 'room_id': 105, 'country': 'US', 'live_type': 'mobile'}, {'date': '2022-10-06', 'creator_id': 2, 'room_id': 106, 'country': 'US', 'live_type': 'pc'}, {'date': '2022-10-31', 'creator_id': 1, 'room_id': 107, 'country': 'US', 'live_type': 'mobile'}, {'date': '2022-11-01', 'creator_id': 1, 'room_id': 108, 'country': 'US', 'live_type': 'mobile'}, {'date': '2022-11-01', 'creator_id': 1, 'room_id': 109, 'country': 'US', 'live_type': 'mobile'}, {'date': '2022-11-01', 'creator_id': 2, 'room_id': 110, 'country': 'US', 'live_type': 'mobile'}, {'date': '2022-11-01', 'creator_id': 2, 'room_id': 111, 'country': 'US', 'live_type': 'mobile'}], [{'date': '2022-10-01', 'room_id': 101, 'watch_cnt': 600, 'gift_recieved_cnt': 10}, {'date': '2022-10-02', 'room_id': 102, 'watch_cnt': 600, 'gift_recieved_cnt': 20}, {'date': '2022-10-03', 'room_id': 103, 'watch_cnt': 600, 'gift_recieved_cnt': 30}, {'date': '2022-10-04', 'room_id': 104, 'watch_cnt': 600, 'gift_recieved_cnt': 40}, {'date': '2022-10-31', 'room_id': 107, 'watch_cnt': 700, 'gift_recieved_cnt': 100}, {'date': '2022-11-01', 'room_id': 108, 'watch_cnt': 500, 'gift_recieved_cnt': 3}, {'date': '2022-11-01', 'room_id': 109, 'watch_cnt': 800, 'gift_recieved_cnt': 4}, {'date': '2022-11-01', 'room_id': 110, 'watch_cnt': 499, 'gift_recieved_cnt': 5}, {'date': '2022-11-01', 'room_id': 111, 'watch_cnt': 500, 'gift_recieved_cnt': 6}], '2022-11-02')
Output: {'q1': {'creator_count': 1}, 'q2': [{'country': 'US', 'creator_id': 1, 'total_gifts_received': 200, 'rank_in_country': 1}, {'country': 'US', 'creator_id': 2, 'total_gifts_received': 0, 'rank_in_country': 2}], 'q3': {'qualified_creator_count': 1}}
Example 2
Input: creator_live_stats([{'date': '2022-10-01', 'creator_id': 10, 'room_id': 1, 'country': 'ID', 'live_type': 'mobile'}, {'date': '2022-10-02', 'creator_id': 11, 'room_id': 2, 'country': 'ID', 'live_type': 'pc'}, {'date': '2022-10-03', 'creator_id': 12, 'room_id': 3, 'country': 'UK', 'live_type': 'mobile'}, {'date': '2022-10-04', 'creator_id': 10, 'room_id': 4, 'country': 'ID', 'live_type': 'pc'}, {'date': '2022-10-05', 'creator_id': 11, 'room_id': 5, 'country': 'ID', 'live_type': 'mobile'}, {'date': '2022-10-06', 'creator_id': 12, 'room_id': 6, 'country': 'UK', 'live_type': 'pc'}], [{'date': '2022-10-01', 'room_id': 1, 'watch_cnt': 1, 'gift_recieved_cnt': 5}, {'date': '2022-10-02', 'room_id': 2, 'watch_cnt': 1, 'gift_recieved_cnt': 5}, {'date': '2022-10-03', 'room_id': 3, 'watch_cnt': 1, 'gift_recieved_cnt': 20}, {'date': '2022-10-04', 'room_id': 4, 'watch_cnt': 1, 'gift_recieved_cnt': 5}, {'date': '2022-10-05', 'room_id': 5, 'watch_cnt': 1, 'gift_recieved_cnt': 5}, {'date': '2022-10-06', 'room_id': 6, 'watch_cnt': 1, 'gift_recieved_cnt': 1}], '2022-10-10')
Output: {'q1': {'creator_count': 0}, 'q2': [{'country': 'ID', 'creator_id': 10, 'total_gifts_received': 10, 'rank_in_country': 1}, {'country': 'ID', 'creator_id': 11, 'total_gifts_received': 10, 'rank_in_country': 2}, {'country': 'UK', 'creator_id': 12, 'total_gifts_received': 21, 'rank_in_country': 1}], 'q3': {'qualified_creator_count': 0}}
Example 3
Input: creator_live_stats([], [], '2023-01-01')
Output: {'q1': {'creator_count': 0}, 'q2': [], 'q3': {'qualified_creator_count': 0}}
Hints
Hint 1
Build a dictionary keyed by (date, room_id) from the activity list so each room can look up its engagement in constant time, falling back to (0, 0) when missing.
Hint 2
For q2, aggregate totals per (country, creator), group these by country, then sort each group with the key (-total, creator_id) and slice the first 5 before assigning ranks 1..5.
Hint 3
For q3, compute yesterday with datetime arithmetic, group that day's rooms by creator, and require both len(rooms) >= 2 and all(watch >= 500) where missing activity means watch = 0.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
All three metrics follow the same pattern: filter the rooms, attach engagement via a (date, room_id) lookup that defaults to zeros, aggregate per creator, then apply a threshold or ranking.
- Lookup. Turn the activity list into a dictionary keyed by
(date, room_id). Looking up a room that is absent gives(0, 0), which mirrors a left join with default values. - Metric 1. Scan the rooms and keep only those in the date window, in the US, on mobile. Count rooms per creator, then count how many creators have a count above 3. No activity data is needed.
- Metric 2. For every October room, add its gifts (0 if unmatched) to the total of its
(country, creator)pair. Group the pairs by country, sort each group by(-total, creator_id), take the first 5, and number them 1 to 5. Iterating countries in sorted order gives the required output order. - Metric 3. Compute yesterday as
run_date - 1 day. Group that day's rooms by creator. A creator qualifies if they have at least 2 rooms and every room haswatch_cnt >= 500, where a missing activity row counts as 0 and so fails the check.
Why it is correct
- Because
(date, room_id)is unique in both lists, the match is one-to-one and nothing is double counted. - Defaulting to zeros keeps rooms without activity in the aggregates: a creator with only unmatched rooms still shows up in the ranking with total 0, and an unmatched room correctly disqualifies a creator in metric 3.
- Sorting by
(-total, creator_id)is a total order, so the top 5 and the ranks are deterministic, and tied totals get distinct consecutive ranks. - Strict comparisons (
> 3) and inclusive ones (>= 2,>= 500, inclusive date window) match the statement exactly. - Keying the ranking on
(country, creator)ranks a creator separately in each country.
Complexity
Let R be the number of rooms and A the number of activity records, and K the number of distinct (country, creator) pairs in October.
- Time: O(R + A + K log K), where the log term comes from sorting within countries.
- Space: O(A + K) for the lookup and the aggregates (plus O(R) for the per-creator grouping in metric 3).
Reference solution
from datetime import date, timedelta
from typing import Dict, List
def creator_live_stats(
live_room: List[Dict[str, object]],
live_room_activity: List[Dict[str, object]],
run_date: str,
) -> Dict[str, object]:
activity = {
(row["date"], row["room_id"]): (
row.get("watch_cnt", 0),
row.get("gift_recieved_cnt", 0),
)
for row in live_room_activity
}
# Metric 1
q1_counts = {}
for room in live_room:
if (
"2022-10-01" <= room["date"] <= "2022-10-07"
and room["country"] == "US"
and room["live_type"] == "mobile"
):
creator = room["creator_id"]
q1_counts[creator] = q1_counts.get(creator, 0) + 1
q1 = sum(1 for count in q1_counts.values() if count > 3)
# Metric 2
totals = {}
for room in live_room:
if room["date"].startswith("2022-10-"):
key = (room["country"], room["creator_id"])
gifts = activity.get((room["date"], room["room_id"]), (0, 0))[1]
totals[key] = totals.get(key, 0) + gifts
by_country = {}
for (country, creator), total in totals.items():
by_country.setdefault(country, []).append((creator, total))
q2 = []
for country in sorted(by_country):
ranked = sorted(by_country[country], key=lambda item: (-item[1], item[0]))
for rank, (creator, total) in enumerate(ranked[:5], 1):
q2.append({
"country": country,
"creator_id": creator,
"total_gifts_received": total,
"rank_in_country": rank,
})
# Metric 3
yesterday = (date.fromisoformat(run_date) - timedelta(days=1)).isoformat()
rooms_by_creator = {}
for room in live_room:
if room["date"] == yesterday:
rooms_by_creator.setdefault(room["creator_id"], []).append(room)
q3 = 0
for rooms in rooms_by_creator.values():
if len(rooms) >= 2 and all(
activity.get((r["date"], r["room_id"]), (0, 0))[0] >= 500
for r in rooms
):
q3 += 1
return {
"q1": {"creator_count": q1},
"q2": q2,
"q3": {"qualified_creator_count": q3},
}