Best Video Category by Mean Watch Time in pandas
SQL & DataModel answerLast updated
Compute which category has the highest mean watch time across valid video rows, with null and nonpositive filtering, name lookup, lexicographic tie-breaks, and rounding.
You have a pandas DataFrame pins with these columns:
pin_id(int)category_id(int)time_spent_sec(float)pin_format(string)
You also have a dictionary category_map that maps each category_id to a human-readable category name.
Write a Python function that returns a tuple (category_name, avg_time) for the category whose average time_spent_sec is highest, considering only rows where pin_format == 'video'.
Rules
- Ignore any row whose
category_idis null or NaN. - Ignore any row whose
time_spent_secis zero or negative (a null or NaN time should also not count). - If two categories have the same average, return the one whose name comes first alphabetically (lexicographically smallest).
- Round
avg_timeto two decimal places. - Target O(n) time and O(k) extra space, where k is the number of distinct categories.
Example
| pin_id | category_id | time_spent_sec | pin_format |
|---|---|---|---|
| 1 | 10 | 12 | video |
| 2 | 10 | 20 | static |
| 3 | 11 | 30 | video |
| 4 | null | 25 | video |
| 5 | 11 | 0 | video |
With category_map = {10: "Food", 11: "Travel"}, the expected result is ("Travel", 30.00).
In your answer, explain your approach, state the complexity, give the code, and discuss the edge cases you would clarify or handle (for example, empty input or ids missing from the map).
Hints
Hint 1
This is a filter, then a group-by-average, then an argmax with a tie-breaker. Think about which per-category running values let you compute an average without storing every row.
Hint 2
Keep two dictionaries keyed by category id: a running sum and a running count. A single pass over the zipped columns fills them, so extra memory depends only on the number of categories.
Hint 3
Comparisons with NaN are always False, so a check like `t <= 0` will not catch NaN. Test for missing values explicitly, and remember an integer column containing NaN becomes float, so cast ids before the lookup.
Hint 4
Compare exact averages when choosing the winner and round only in the returned value. Decide in advance what to return when nothing qualifies.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The task is a filtered group-by followed by an argmax with a deterministic tie-break. To stay within O(n) time and O(k) extra space, make one pass over the rows and maintain two hash maps keyed by category_id:
sums[cid]: total watch time of qualifying rowscounts[cid]: number of qualifying rows
A row qualifies only if all of these hold:
pin_format == 'video'category_idis not null or NaNtime_spent_secis not null or NaN, and is greater than 0
After the pass, iterate over the at most k categories, compute sum / count, look up the name, and keep the best candidate under this ordering: higher average wins, and on an exact tie the lexicographically smaller name wins. Round only when returning.
Walking through the sample: row 1 (Food, 12) is kept; row 2 is static and dropped; row 3 (Travel, 30) is kept; row 4 has a null category and is dropped; row 5 has time 0 and is dropped. Food averages 12 and Travel averages 30, so the answer is ("Travel", 30.0).
Code
import pandas as pd
def top_video_category(pins: pd.DataFrame, category_map: dict):
sums, counts = {}, {}
for cid, t, fmt in zip(pins["category_id"],
pins["time_spent_sec"],
pins["pin_format"]):
if fmt != "video":
continue
if cid is None or pd.isna(cid):
continue
if t is None or pd.isna(t) or t <= 0:
continue
cid = int(cid) # ids become floats once NaN is present
sums[cid] = sums.get(cid, 0.0) + float(t)
counts[cid] = counts.get(cid, 0) + 1
best_name, best_avg = None, None
for cid, total in sums.items():
name = category_map.get(cid)
if name is None: # unmapped id: skip (state this choice)
continue
avg = total / counts[cid]
if (best_avg is None
or avg > best_avg
or (avg == best_avg and name < best_name)):
best_name, best_avg = name, avg
if best_name is None:
return None
return (best_name, round(best_avg, 2))
Why it is correct
- Filtering happens before aggregation. Invalid rows never touch the sums or counts, so each average covers exactly the qualifying rows.
- NaN needs an explicit check. Any comparison with NaN is False, so
t <= 0alone lets NaN through. Usepd.isnafor both the category id and the time. - Type upcasting. An integer column containing NaN becomes
float64, so ids arrive as10.0. Casting withint()makes the dictionary lookup explicit and clean. - Deterministic tie-break. The condition
avg > best_avg or (avg == best_avg and name < best_name)is a strict total order, so the result does not depend on dictionary iteration order. - Round last. Rounding before comparing can create false ties (for example 30.004 and 29.996 both become 30.00). Compare exact averages and round once at the end. If the requirement is that ties are judged on rounded values, compare
round(avg, 2)instead. This is worth asking about.
Complexity
- Time: O(n) for one pass with O(1) hash updates, plus O(k) to pick the winner.
- Space: O(k) for the two dictionaries. Zipping the existing columns streams values without creating a filtered copy of the DataFrame.
Idiomatic pandas alternative
v = pins[(pins.pin_format == "video")
& pins.category_id.notna()
& (pins.time_spent_sec > 0)]
avg = v.groupby("category_id")["time_spent_sec"].mean()
This is shorter and more readable and is also O(n) time, but the boolean mask and filtered frame use O(n) extra memory. It is a reasonable production choice, while the single pass is the one that meets the stated O(k) space bound. If you use idxmax, handle ties explicitly, because it returns the first maximum it encounters rather than the alphabetically smallest name.
Edge cases
- No qualifying rows (empty frame, no videos, everything filtered): return
Noneand say so, rather than raising. - Category id missing from the map: this version skips it. An alternative is falling back to
str(cid). Either is fine if stated. - Two ids sharing one name: they are treated as separate categories. If the name is the true grouping key, aggregate by name instead.
- Format casing or whitespace (
"Video"," video"): the spec says exact match. Offer.strip().lower()if the data is messy. - Display:
round(30.0, 2)returns30.0, which equals 30.00. Usef"{avg:.2f}"only if a string is needed. - Negative times: excluded by the
> 0rule, just like zero.
Common mistakes
- Relying on
t <= 0and letting NaN times through. - Rounding before comparing averages.
- Using
idxmaxand getting an arbitrary tie winner. - Averaging per-row averages instead of dividing total time by total count.
- Forgetting to define behavior for empty results.
Testing
Beyond the sample, test a tie (two categories both averaging 15.0 should return the alphabetically first name), a frame with no videos, a frame with only invalid rows, and an id absent from the map.