progress

~/problems / Heaps / Heaps and priority queues

Top ads in a time window

On a phone? Coding is easier on a laptop: email this problem to yourself . Meanwhile: quiz this topic or fight a boss.

easy ~15 min Pinterest

An ad server logs one record per impression as [timestamp, ad_id], both strings. Timestamps are non-negative decimal integers, possibly with leading zeros ("0042" is 42). Records are not sorted.

Implement:

def most_common_ads(impressions: list[list[str]], k: int, start: int, end: int) -> list[str]

Count only records with start <= t <= end, comparing as numbers. Return the k ad ids shown most often, most first; ties go by ad_id in Python string order (case-sensitive, "B" before "a"). If fewer than k ads appear, return them all.

log = [["10", "shoes"], ["3", "tea"], ["12", "shoes"], ["007", "tea"],
       ["11", "lamp"], ["9", "lamp"], ["20", "shoes"], ["8", "tea"]]
most_common_ads(log, 2, 5, 12)    # ["lamp", "shoes"]   window 5..12: lamp 2, shoes 2, tea 2 -> ties by name
most_common_ads(log, 1, 0, 100)   # ["shoes"]           shoes 3, tea 3 -> "shoes" < "tea"
most_common_ads(log, 5, 13, 19)   # []

⭐ Bonus: a speed test with 200,000 records earns a star if you count in one pass instead of rescanning the log once per ad.

Show hint

Count with a dictionary, then pick the k best with a heap keyed on (-count, ad_id), or sort when k is large.

Topic: Heaps and priority queues. heapq: top-k, k-way merge, two heaps for a running median.

Read the visual guide
0:00
Ctrl ' run · Ctrl ↵ submit
esc