Trailing-Day Campaign CTR over Two Skewed Event Feeds
Data Structure DesignModel answerLast updated
Build a generator that emits per-campaign impression, click and CTR figures over a trailing 24-hour window, counting one click per impression and accepting events up to 10 minutes late.
Live CTR for every campaign
An ad system produces two feeds, exposed as Python iterators of dictionaries. Each feed is sorted by non-decreasing ts, an ISO 8601 string.
- Impression:
{"imp_id", "campaign_id", "ts"} - Click:
{"click_id", "imp_id", "campaign_id", "ts"}
Write a generator that maintains, for each campaign, the number of impressions, the number of de-duplicated clicks and the click-through rate over the trailing 24 hours. It should yield a record whenever a campaign's figures change.
Rules
- One click per impression. If several clicks reference the same
imp_id, only the one with the earliesttscounts. Clicks whoseimp_idnever appears in the impression feed are ignored. - Event time. Each event is placed in the window by its own
ts. The window ends at the largesttsseen so far and extends 24 hours back. - Late events. An event can arrive up to 10 minutes behind the newest timestamp. If its
tsis still inside the window, it must be counted. - Output. Yield
(ts, campaign_id, impressions_in_window, dedup_clicks_in_window, ctr_in_window)only when that campaign's counts have changed. - Cost. Amortized O(log n) per event, with memory proportional to the events inside the window. Justify this with a big-O argument.
Edge cases to cover
- Multiple clicks on the same impression, including a later-arriving click with an earlier timestamp.
- Skew between the feeds, for example a click that is seen before its impression.
- Daylight-saving transitions and mixed UTC offsets in the timestamps.
Deliverables
Provide the code, a short description of your data structures, and an explanation of how late events and expiry are handled. State assumptions wherever the rules are ambiguous.
Hints
Hint 1
Convert every timestamp to a timezone-aware UTC datetime up front. Daylight saving then stops mattering, and the window is always exactly 24 elapsed hours.
Hint 2
Use hash maps for lookups (imp_id to impression, imp_id to its counted click) and min-heaps keyed by timestamp for expiry. Late events break arrival order, so a plain FIFO deque is not enough.
Hint 3
A click can arrive before its impression. Hold unmatched clicks in a pending map for 10 minutes. When replacing a click, leave the old heap entry in place and, when it is popped, check it against the current map value (lazy deletion).
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Assumptions
- Event time.
nowis the maximumtsseen so far, and the window is(now - 24h, now]. - Counting. An impression counts while its own
tsis in the window, and so does a click. - Timestamps. Every string is parsed to a UTC-aware
datetime, and naive strings are treated as UTC. In UTC,01:30-04:00and01:30-05:00are different instants and a day is always 24 hours, so DST needs no special code. - Lateness. An event with
ts < now - 10 min, or one already outside the window, is out of contract and dropped. - Dedup. Per
imp_id, the click with the smallesttswins. A late click with an earliertsreplaces the stored one. - Early clicks. A click that arrives before its impression waits in a pending buffer for up to 10 minutes. If the impression arrives, the click is applied. Otherwise it expires and is ignored.
- Matching. A click is matched only against impressions still in the window, so a click on an impression older than 24 hours is ignored. The click's own
campaign_idis used for attribution. - Interleaving. I merge the two feeds by
ts. The event handler does not rely on global order and tolerates the 10-minute regression, so it also works if the feeds are consumed in a different interleaving.
Data structures
| Structure | Role |
|---|---|
imps: imp_id -> (ts, campaign) | Impressions currently in the window |
imp_heap: (ts, imp_id) | Expires impressions in time order |
clicks: imp_id -> (ts, campaign) | The one counted click per impression |
click_heap: (ts, imp_id) | Expires clicks; stale entries are skipped |
pending, pend_heap | Clicks waiting for their impression, dropped after 10 minutes |
n_imp, n_clk: campaign -> int | Live counters |
last: campaign -> (imps, clicks) | Last emitted values, to suppress no-op output |
Heaps are used rather than deques because late events make insertion order differ from timestamp order. Replacing a click leaves its old heap entry behind. When that entry is popped, it is discarded unless clicks[imp_id] still has the same ts.
Code
import heapq
from collections import defaultdict
from datetime import datetime, timedelta, timezone
WINDOW = timedelta(hours=24)
LATE = timedelta(minutes=10)
def parse(s):
d = datetime.fromisoformat(s.replace("Z", "+00:00"))
if d.tzinfo is None:
d = d.replace(tzinfo=timezone.utc)
return d.astimezone(timezone.utc)
def stream_ctr(impressions, clicks_iter):
src_i = (("i", parse(e["ts"]), e) for e in impressions)
src_c = (("c", parse(e["ts"]), e) for e in clicks_iter)
merged = heapq.merge(src_i, src_c, key=lambda t: t[1])
imps, imp_heap = {}, []
clicks, click_heap = {}, []
pending, pend_heap = {}, []
n_imp, n_clk = defaultdict(int), defaultdict(int)
last, dirty = {}, set()
now = None
def set_click(iid, ts, camp):
old = clicks.get(iid)
if old is not None:
if old[0] <= ts:
return # keep earliest click
n_clk[old[1]] -= 1
dirty.add(old[1])
clicks[iid] = (ts, camp)
heapq.heappush(click_heap, (ts, iid))
n_clk[camp] += 1
dirty.add(camp)
def expire():
cutoff = now - WINDOW
while imp_heap and imp_heap[0][0] <= cutoff:
_, iid = heapq.heappop(imp_heap)
_, camp = imps.pop(iid)
n_imp[camp] -= 1
dirty.add(camp)
while click_heap and click_heap[0][0] <= cutoff:
ts, iid = heapq.heappop(click_heap)
cur = clicks.get(iid)
if cur is not None and cur[0] == ts: # skip stale entries
del clicks[iid]
n_clk[cur[1]] -= 1
dirty.add(cur[1])
while pend_heap and pend_heap[0][0] < now - LATE:
ts, iid = heapq.heappop(pend_heap)
cur = pending.get(iid)
if cur is not None and cur[0] == ts:
del pending[iid]
for kind, ts, e in merged:
if now is None or ts > now:
now = ts
if ts <= now - WINDOW or ts < now - LATE:
continue # out of contract
iid = e["imp_id"]
if kind == "i":
if iid not in imps:
imps[iid] = (ts, e["campaign_id"])
heapq.heappush(imp_heap, (ts, iid))
n_imp[e["campaign_id"]] += 1
dirty.add(e["campaign_id"])
p = pending.pop(iid, None)
if p is not None:
set_click(iid, p[0], p[1])
else:
if iid in imps:
set_click(iid, ts, e["campaign_id"])
else:
p = pending.get(iid)
if p is None or ts < p[0]:
pending[iid] = (ts, e["campaign_id"])
heapq.heappush(pend_heap, (ts, iid))
expire()
for camp in sorted(dirty):
cur = (n_imp[camp], n_clk[camp])
if last.get(camp) != cur:
last[camp] = cur
ctr = cur[1] / cur[0] if cur[0] else 0.0
yield (now.isoformat(), camp, cur[0], cur[1], ctr)
dirty.clear()
Complexity
- Each event causes a constant number of heap pushes (impression, click, pending) and dict operations. Each heap entry is popped at most once. That gives O(log n) amortized per event, where n is the number of live entries.
- Counters and the
lastmap are O(1) per update. Emitting touches only campaigns marked dirty by that event. - Memory is O(events in the last 24 hours). The pending buffer holds at most 10 minutes of clicks. Stale click-heap entries are bounded by the number of replacements inside the window and are removed when their timestamp expires.
Edge cases
- Duplicate clicks. The first click is stored. Any later click replaces it only if its
tsis strictly earlier. The counter stays at 1, and a replacement changes the expiry time without changing the emitted counts. - Click before impression. The click sits in
pendingand is promoted when the impression arrives within the 10-minute bound. - Replaced click expiring. The old heap entry's
tsno longer matches the map, so it is skipped and cannot decrement a counter twice. - DST and offsets. Everything is normalized to UTC, so the autumn "repeated hour" yields two distinct instants and the window never becomes 23 or 25 hours.
- Zero impressions. CTR is reported as 0.0 rather than dividing by zero.
Common mistakes
- Using a deque and assuming insertion order equals expiry order.
- Decrementing counters for a stale heap entry (no lazy-deletion check).
- Parsing timestamps as naive local times.
- Emitting on every event rather than only when a campaign's counts changed.
- Discarding early clicks immediately, which loses real clicks whenever the feeds are skewed.