KatInterview

Top Opening Film Across Subscriber Watch Logs

SQL & DataAuto-graded · 18 test cases
MediumAuto-gradedSQL & Datahash-mapaggregationtie-breaking

Last updated

Find each user's earliest-watched title, then pick the title that opens the most users' histories, using deterministic tie-breaking rules.

A streaming service keeps a log of what its subscribers have watched. Each log entry is a list of three values: [customer_id, title, date], where date is an ISO-8601 string such as "2025-01-01".

For each customer, the opening film is the title of that customer's earliest-dated entry. Your task is to return the title that is the opening film for the largest number of distinct customers.

Rules

  • Each customer contributes exactly one opening film, no matter how many entries they have.
  • If a customer has several entries on their earliest date, their opening film is the one whose title is alphabetically smallest (standard string comparison).
  • If several titles tie for the highest number of customers, return the alphabetically smallest of them.
  • If the log is empty, return None.
  • The entries may appear in any order; do not assume they are sorted.
  • Only opening films are counted. A title with many total views but few opening views does not gain from its other views.
  • A customer who watches the same title repeatedly still counts at most once.

Input

  • entries: a list of [customer_id, title, date] lists.

Output

  • The winning title as a string, or None if entries is empty.

Constraints

  • 0 <= len(entries) <= 10^5
  • customer_id is an integer.
  • title is a string.
  • date values are ISO-8601 strings (YYYY-MM-DD), so lexicographic order matches chronological order.
  • The expected solution runs in roughly linear time.

Examples

Example 1

Input: top_opening_film([[1, 'Toy Story', '2025-01-01'], [1, 'Avengers', '2025-01-10'], [2, 'Avengers', '2025-01-02']])

Output: 'Avengers'

Example 2

Input: top_opening_film([[1, 'Dune', '2025-02-01'], [2, 'Avatar', '2025-01-01'], [3, 'Dune', '2025-01-03'], [4, 'Avatar', '2025-01-04']])

Output: 'Avatar'

Example 3

Input: top_opening_film([[10, 'The Matrix', '2024-05-01'], [10, 'Alien', '2024-05-01'], [11, 'Alien', '2024-05-02']])

Output: 'Alien'

Hints

Hint 1

Handle the problem in two stages: first shrink the log to one row per customer, then count over those rows.

Hint 2

To find each customer's opening film, compare (date, title) pairs. Taking the smaller pair handles both the earliest date and the same-day alphabetical rule.

Hint 3

When choosing the final title, rank by highest count and then by smallest title. Use a key such as (-count, title) so the result does not depend on insertion order.