KatInterview

Count Distinct Engaged Ads Per Day from an Event Log

Arrays & HashingAuto-graded · 22 test cases
EasyAuto-gradedArrays & Hashinghash-mapsetgrouping

Last updated

Tests filtering an event log by type, grouping by date, counting distinct ids with sets, and returning date-sorted results while omitting dates that have no qualifying events.

Daily Engaged Ads

You have a log of advertisement events. Each entry is a list [ad_id, event_type, event_date]:

  • ad_id is an integer identifying the ad.
  • event_type is a string, such as "click", "impression", or "view".
  • event_date is a string in YYYY-MM-DD format.

An ad counts as engaged on a given date if the log contains at least one event for that ad on that date whose event_type is exactly "click" or "impression". Events of any other type are ignored completely.

Task

Write a function that returns, for every date that has at least one engaged ad, the number of distinct engaged ads on that date.

Output format

  • Return a list of [event_date, engaged_ad_count] pairs.
  • Sort the pairs by event_date ascending (chronological order).
  • Dates with no engaged ads must not appear in the result, even if the log contains other events (such as "view") on those dates.
  • If no date qualifies, return an empty list.

Rules

  • An ad with several qualifying events on the same date, in any mix of clicks and impressions, counts once for that date.
  • Identical duplicate rows count once.
  • The same ad can be engaged on several different dates; it counts once on each of them.
  • Event type matching is case-sensitive, so "Click" is not "click".
  • The input may be in any order.

Constraints

  • 0 <= len(rows) <= 10^5
  • ad_id is an integer.
  • event_date is always a valid YYYY-MM-DD string.
  • event_type is an arbitrary string; only "click" and "impression" qualify.

Examples

Example 1

Input: count_daily_engaged_ads([[101, 'click', '2023-10-01'], [101, 'view', '2023-10-01'], [102, 'impression', '2023-10-01'], [101, 'view', '2023-10-02']])

Output: [['2023-10-01', 2]]

Example 2

Input: count_daily_engaged_ads([[1, 'click', '2023-10-01'], [1, 'impression', '2023-10-01'], [2, 'click', '2023-10-01'], [3, 'view', '2023-10-02']])

Output: [['2023-10-01', 2]]

Hints

Hint 1

Think of the task as three steps: filter the rows, group them by date, then count unique ad ids per group.

Hint 2

Keep a mapping from date to a set of ad ids. Adding to a set automatically ignores repeats, so you get distinct counts for free.

Hint 3

Accept only the two qualifying event types, so dates holding only other events never get an entry. Because dates are YYYY-MM-DD strings, sorting them as plain strings gives chronological order.