Most Frequent Ads Within a Closed Time Range
Heaps, Sorting & SearchAuto-graded · 22 test casesLast 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_idcomes first. - If fewer than
kdistinct 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^5eventsis 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, andend_time_ms - window_msmay be negative.kis 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.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
- Return
[]right away ifk <= 0or the log is empty. - Extract the timestamps into a separate list. Since the log is sorted, so is this list.
- Compute
start = end_time_ms - window_ms. Usebisect_leftto find the index of the first event with timestamp>= start, andbisect_rightto find the index of the first event with timestamp> end_time_ms. The slice between these two indices contains exactly the in-range events. - Count how many times each ad ID appears in that slice using a hash map.
- Sort the
(ad_id, count)pairs by(-count, ad_id): higher count first, smaller ID first on ties. - Return the IDs of the first
kpairs.
Why it is correct
bisect_leftfor the lower edge keeps events whose timestamp equalsstart;bisect_rightfor the upper edge keeps events whose timestamp equalsend_time_ms. Together they select exactly the closed interval, including duplicates of boundary timestamps.- Sorting by
(-count, ad_id)is a total order over distinct ads, so the output is unique and deterministic and matches the tie-break rule. - Slicing the ranked list to
kreturns all ads when there are fewer thank, and an empty window gives an empty counter, hence[].
Complexity
Let n be the number of events, w the number in range, and u the number of distinct ads in range.
- Time:
O(n + w + u log u). Building the timestamp list isO(n), the two binary searches areO(log n), counting isO(w), and sorting isO(u log u). Usingheapq.nsmallestfor the final selection would giveO(u log k). - Space:
O(n + u).
Reference solution
from bisect import bisect_left, bisect_right
from collections import Counter
from typing import List
def top_ads_in_range(events: List[List[int]], window_ms: int, end_time_ms: int, k: int) -> List[int]:
if k <= 0 or not events:
return []
timestamps = [event[0] for event in events]
start_time = end_time_ms - window_ms
left = bisect_left(timestamps, start_time)
right = bisect_right(timestamps, end_time_ms)
counts = Counter(ad_id for _, ad_id in events[left:right])
ranked = sorted(counts.items(), key=lambda item: (-item[1], item[0]))
return [ad_id for ad_id, _ in ranked[:k]]