Monthly Hit Tracks: Overall and Per-Region Leaderboards
Arrays & HashingAuto-graded · 16 test casesLast updated
Filter streaming events by duration and date window, count plays per track, and produce a global top 5 and per-country top 3 with deterministic tie-breaking.
Monthly Hit Tracks
A music app records every listening session as an event. You are building a popularity report for January 2024 that covers the whole world and each individual country.
Write a function monthly_top_tracks(events). The argument events is a list of dictionaries. Each dictionary describes one listening event and may contain these keys:
event_id: unique identifier of the eventuser_id: the listenertrack_id: the track that was played (integer, may be missing orNone)country_code: two-letter country code (string, may be missing orNone)played_at: when the play happened, either an ISO-style string such as"2024-01-05 12:00:00"or adatetimeobject (may be missing orNone)duration_secs: how many seconds were listened to (integer, may be missing orNone)
What counts as a valid play
An event is counted only if all of the following hold:
duration_secsis present and is at least 30 (exactly 30 counts, 29 does not).played_atis present and lies between2024-01-01 00:00:00and2024-01-31 23:59:59, with both ends included.track_idis present (notNone).country_codeis present (notNone).
Events that fail any of these checks are ignored for both results below.
What to return
Return a dictionary with exactly two keys:
-
"global_top_5": a list of[track_id, play_count]pairs for the 5 tracks with the most valid plays worldwide. Sort byplay_countdescending; if counts are equal, the smallertrack_idcomes first. If fewer than 5 tracks have valid plays, return all of them. -
"country_top_3": a list of[country_code, track_id, play_count, rank]rows. For each country, take the 3 tracks with the most valid plays in that country, using the same ordering (count descending, thentrack_idascending), and give them ranks 1, 2, 3 in that order. Ranks are always consecutive integers; tied tracks do not share a rank. If a country has fewer than 3 distinct played tracks, include all of them. Rows are ordered bycountry_codeascending, thenrankascending.
If no valid plays exist, both lists are empty.
Constraints
0 <= len(events) <= 10^5track_idvalues are integers;country_codevalues are strings.played_atstrings are parseable bydatetime.fromisoformat.- Ties are always resolved by the smaller
track_id. - Counting is per valid event; each event contributes at most one play.
Examples
Example 1
Input: monthly_top_tracks([{'event_id': 1, 'user_id': 10, 'track_id': 1042, 'country_code': 'BR', 'played_at': '2024-01-05 12:00:00', 'duration_secs': 45}, {'event_id': 2, 'user_id': 11, 'track_id': 2011, 'country_code': 'BR', 'played_at': '2024-01-06 12:00:00', 'duration_secs': 35}, {'event_id': 3, 'user_id': 12, 'track_id': 105, 'country_code': 'SE', 'played_at': '2024-01-10 09:30:00', 'duration_secs': 30}, {'event_id': 4, 'user_id': 13, 'track_id': 1042, 'country_code': 'BR', 'played_at': '2024-01-31 23:59:59', 'duration_secs': 60}, {'event_id': 5, 'user_id': 14, 'track_id': 9901, 'country_code': 'SE', 'played_at': '2024-02-01 00:00:00', 'duration_secs': 50}, {'event_id': 6, 'user_id': 15, 'track_id': 451, 'country_code': 'BR', 'played_at': '2024-01-15 08:00:00', 'duration_secs': 29}])
Output: {'global_top_5': [[1042, 2], [105, 1], [2011, 1]], 'country_top_3': [['BR', 1042, 2, 1], ['BR', 2011, 1, 2], ['SE', 105, 1, 1]]}
Hints
Hint 1
Decide first which events are valid. Do all the filtering (duration, date window, missing track or country) in one pass before thinking about ranking.
Hint 2
While scanning, keep one counter keyed by track for the global result and one counter per country keyed by track for the regional result.
Hint 3
Sort each counter's items with the key (-count, track_id) and slice to 5 or 3. Assign ranks with enumerate starting at 1, and iterate countries in sorted order.
Worked solution
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Both outputs follow the same pipeline: filter, count, order, cut.
- Filter. Walk through the events once and skip any that is not a valid play: missing or short duration, missing or out-of-window timestamp, or missing track or country. String timestamps are converted to
datetimefirst so the window comparison is correct, with both boundaries inclusive. - Count. For each valid event, increment a global counter keyed by
track_idand a per-country counter keyed bytrack_id. - Order. Sort counter items by the key
(-count, track_id). This is a total order, because track IDs are distinct within a counter, so the result is fully deterministic. - Cut. Keep the first 5 global entries. For each country (visited in sorted order), keep the first 3 entries and number them 1, 2, 3 with
enumerate.
Why it is correct
- Every increment happens only after all validity checks pass, so each count equals the number of valid plays.
- Because invalid events are dropped before either counter is touched, the global and per-country results are consistent with each other.
- The sort key puts higher counts first and breaks ties with the lower
track_id, exactly as specified. - Slicing handles the "fewer than 5 / fewer than 3" cases automatically, and an empty input yields empty lists.
- Iterating
sorted(country_counts)and emitting ranks in ascending order produces the required row ordering.
Complexity
Let N be the number of events, T the number of distinct tracks, and P the number of distinct (country, track) pairs.
- Time: O(N) for filtering and counting, plus O(T log T + P log P) for sorting.
- Space: O(T + P) for the counters.
Reference solution
from collections import Counter, defaultdict
from datetime import datetime
from typing import Dict, List
def monthly_top_tracks(events: List[Dict]) -> Dict:
start = datetime.fromisoformat("2024-01-01 00:00:00")
end = datetime.fromisoformat("2024-01-31 23:59:59")
global_counts = Counter()
country_counts = defaultdict(Counter)
for event in events:
duration = event.get("duration_secs")
played_at = event.get("played_at")
if duration is None or duration < 30 or played_at is None:
continue
if isinstance(played_at, str):
played_at = datetime.fromisoformat(played_at)
if not start <= played_at <= end:
continue
track_id = event.get("track_id")
country = event.get("country_code")
if track_id is None or country is None:
continue
global_counts[track_id] += 1
country_counts[country][track_id] += 1
global_top = [
[track_id, count]
for track_id, count in sorted(
global_counts.items(), key=lambda item: (-item[1], item[0])
)[:5]
]
country_top = []
for country in sorted(country_counts):
ranked = sorted(
country_counts[country].items(), key=lambda item: (-item[1], item[0])
)[:3]
for rank, (track_id, count) in enumerate(ranked, 1):
country_top.append([country, track_id, count, rank])
return {"global_top_5": global_top, "country_top_3": country_top}