KatInterview

Trailing-Day Campaign CTR over Two Skewed Event Feeds

Data Structure DesignModel answer
MediumModel answerData Structure Designstreamingsliding-windowheap

Last 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 earliest ts counts. Clicks whose imp_id never 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 largest ts seen so far and extends 24 hours back.
  • Late events. An event can arrive up to 10 minutes behind the newest timestamp. If its ts is 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).