Distinct Content Categories per Reader
SQL & DataAuto-graded · 20 test casesLast updated
Tests two-level aggregation: counting distinct content categories per reader on a target date, then bucketing those counts into a frequency histogram across all dates.
Distinct Content Categories per Reader
You are given two datasets describing reader activity on a content platform.
Dataset 1: read_events — one row per reading event.
| Field | Type | Description |
|---|---|---|
user_id | int | Reader who opened the content |
content_id | int | Piece of content that was opened |
read_date | str | Calendar date of the event ("YYYY-MM-DD") |
Dataset 2: content_catalog — maps each piece of content to a category.
| Field | Type | Description |
|---|---|---|
content_id | int | Content identifier |
category | str | Category the content belongs to |
Every content_id in read_events is guaranteed to appear in content_catalog.
If a reader opens several pieces of content that all belong to the same category, that category is still counted only once for that reader.
Part 1 — Snapshot for a single date
For the date "2019-01-01", compute how many distinct categories each reader encountered. Return one row per reader who had at least one reading event on that date.
Output format: a list of [user_id, num_categories], sorted ascending by user_id.
Part 2 — Histogram across all dates
Using every reading event in the dataset (no date filter), compute each reader's total number of distinct categories across their full history. Then build a histogram: for each observed value of num_categories, count how many readers have exactly that value.
Output format: a list of [num_categories, num_readers], sorted ascending by num_categories. Only include values of num_categories that at least one reader has; do not emit zero-filled buckets.
Return value
Return a single dict with two keys:
{
"daily": [[user_id, num_categories], ...], # Part 1
"histogram": [[num_categories, num_readers], ...] # Part 2
}
Constraints
1 <= len(read_events) <= 10^51 <= len(content_catalog) <= 10^4user_idandcontent_idare positive integers.read_dateis a string in"YYYY-MM-DD"format.- Multiple rows in
read_eventsmay share the same(user_id, content_id, read_date)triple (duplicate events); they do not inflate the distinct-category count. - A reader absent from
"2019-01-01"does not appear in the"daily"output but is included in"histogram"if they have events on other dates. - The number of distinct categories across all content is small relative to the number of events.
Examples
Example 1
Input: count_distinct_categories([[1, 101, '2019-01-01'], [1, 102, '2019-01-01'], [1, 103, '2019-01-02'], [2, 101, '2019-01-01'], [2, 103, '2019-01-03'], [3, 104, '2019-01-02']], [[101, 'news'], [102, 'news'], [103, 'technology'], [104, 'news']])
Output: {'daily': [[1, 1], [2, 1]], 'histogram': [[1, 1], [2, 2]]}
Hints
Hint 1
Build a lookup table from content_catalog first (content_id → category). This plays the role of a JOIN and lets you process read_events in a single pass.
Hint 2
For Part 1, track a set of categories per user, but only for rows where read_date equals '2019-01-01'. For Part 2, do the same thing with no date filter — a user's all-time set must include every date, not just the target date.
Hint 3
The histogram is an aggregation of an aggregation. First reduce each user to the size of their all-time set (one integer per user), then count how many users share each integer value. Trying to do both in one pass is the most common mistake.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Core insight: aggregation of an aggregation
Part 1 is a straightforward group-by with a distinctness requirement. Part 2 is trickier because it asks for a histogram — a count of counts. That means you need two separate aggregation steps, and conflating them is the most common error.
Step-by-step
Build the lookup. Convert content_catalog into a dict mapping content_id → category. This is the equivalent of a SQL JOIN and costs O(C) time and space, where C is the number of catalog rows.
Single pass over events. For each reading event:
- Resolve its category via the lookup.
- Add the category to the reader's all-time set (
all_sets). Using asetautomatically deduplicates: viewing five "Sports" articles still contributes one category. - If the event's date is
"2019-01-01", also add the category to the reader's daily set (daily_sets).
One scan fills both structures simultaneously, keeping the constant factor low.
Part 1 output. Iterate over daily_sets, take the length of each set (that is the distinct count), and sort the pairs by user_id.
Part 2 output. Collect len(s) for every set in all_sets — one integer per reader. Feed those integers to Counter to get the histogram buckets, then sort by bucket value. Only buckets with at least one reader appear, which satisfies the "no zero-filled rows" requirement.
Why this is correct
- Distinctness is enforced by the
setdata structure. Duplicate events, multiple articles in the same category, and repeat views across different dates are all absorbed. - Part 1 scope: the
if read_date == TARGETguard means only events from that day feeddaily_sets. A reader absent on that day has no entry, matching the requirement to omit them. - Part 2 scope:
all_setsis built without any date filter, so every event contributes. Each reader maps to exactly one histogram bucket. - No zero buckets:
Counteronly stores keys with positive counts, so the output never includes a[k, 0]row.
Complexity
Let V = number of view events, C = number of catalog entries, U = number of distinct readers, K = number of distinct histogram buckets.
- Time: O(C) to build the lookup + O(V) for the event scan + O(U log U) to sort the daily output + O(K log K) to sort the histogram. Dominant term is O(V + U log U).
- Space: O(C) for the category map + O(V) worst-case for all the sets (if every event is a unique
(user, category)pair).
Reference solution
from collections import Counter, defaultdict
from typing import Dict, List
def count_distinct_categories(read_events: List[List], content_catalog: List[List]) -> Dict[str, List[List[int]]]:
# Build a content_id -> category lookup (equivalent to the JOIN)
category_map = {content_id: category for content_id, category in content_catalog}
daily_sets = defaultdict(set) # user_id -> distinct categories on 2019-01-01
all_sets = defaultdict(set) # user_id -> distinct categories across all dates
TARGET = "2019-01-01"
for user_id, content_id, read_date in read_events:
category = category_map[content_id]
all_sets[user_id].add(category)
if read_date == TARGET:
daily_sets[user_id].add(category)
# Part 1: one entry per user active on the target date, sorted by user_id
daily = [[user_id, len(cats)] for user_id, cats in sorted(daily_sets.items())]
# Part 2: aggregate-of-aggregate — bucket users by their all-time distinct count
histogram_counter = Counter(len(cats) for cats in all_sets.values())
histogram = [[count, histogram_counter[count]] for count in sorted(histogram_counter)]
return {"daily": daily, "histogram": histogram}