KatInterview

Best Video Category by Mean Watch Time in pandas

SQL & DataModel answer
MediumModel answerSQL & Datapandasaggregationhash-map

Last 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_id is null or NaN.
  • Ignore any row whose time_spent_sec is 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_time to two decimal places.
  • Target O(n) time and O(k) extra space, where k is the number of distinct categories.

Example

pin_idcategory_idtime_spent_secpin_format
11012video
21020static
31130video
4null25video
5110video

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.