KatInterview

Most Frequent Ads Within a Closed Time Range

Heaps, Sorting & SearchAuto-graded · 22 test cases
MediumAuto-gradedHeaps, Sorting & Searchbinary-searchhash-mapsorting

Last updated

Select the K most frequent ad IDs among timestamped impressions in an inclusive window, breaking ties by smaller ID; tests binary search on sorted data plus counting and ordering.

Most Frequent Ads Within a Closed Time Range

An ad server records every time an ad is shown. Each record is a pair [timestamp_ms, ad_id], and the whole log is sorted by timestamp_ms in non-decreasing order.

You are asked to report the most frequently shown ads inside a recent time range that ends at a given moment.

Task

Write a function that receives:

  • events: the impression log, a list of [timestamp_ms, ad_id] pairs sorted by timestamp.
  • window_ms: the length of the look-back range in milliseconds.
  • end_time_ms: the moment at which the range ends.
  • k: how many ad IDs to return.

An impression is in range if its timestamp t satisfies

end_time_ms - window_ms <= t <= end_time_ms

Both ends are inclusive.

Count the in-range impressions for each ad ID and return the IDs of the k ads with the highest counts, ordered from most to least frequent.

Rules

  • If two ads have the same count, the one with the smaller ad_id comes first.
  • If fewer than k distinct ads appear in range, return all of them in ranked order (do not pad).
  • If no impressions are in range, the log is empty, or k <= 0, return an empty list.
  • The returned list contains only ad IDs, not counts.

Constraints

  • 0 <= len(events) <= 2 * 10^5
  • events is sorted by timestamp in non-decreasing order; several events may share a timestamp.
  • Timestamps, window_ms, end_time_ms, and ad IDs are integers.
  • window_ms >= 0, and end_time_ms - window_ms may be negative.
  • k is an integer and may be zero or larger than the number of distinct ads.

Examples

Example 1

Input: top_ads_in_range([[1000, 101], [1100, 102], [1200, 101], [1500, 103], [1600, 102]], 500, 1500, 2)

Output: [101, 102]

Example 2

Input: top_ads_in_range([[1, 7], [2, 7], [3, 8], [4, 9]], 3, 4, 3)

Output: [7, 8, 9]

Example 3

Input: top_ads_in_range([[100, 5], [200, 5], [300, 2], [400, 2], [500, 3]], 400, 500, 2)

Output: [2, 5]

Hints

Hint 1

Because the log is sorted by timestamp, the in-range events form one contiguous block. You can locate its edges without scanning everything.

Hint 2

Use a lower-bound binary search for the first timestamp >= end_time_ms - window_ms and an upper-bound search for the first timestamp > end_time_ms, so both ends stay inclusive.

Hint 3

Count ad IDs in that block with a hash map, then sort by (-count, ad_id) and take the first k. A heap of size k also works.