p102 — Design Hit Counter — Hints
-
Memory must be bounded by the window, not by total hits. A naive
listgrows forever. A deque is bounded but only aftergetHits(or a cleanup step onhit) actually pops the old entries. -
Two designs cover the spectrum. (a)
dequeof timestamps —hitappend,getHitspopleft-while-stale thenlen. (b) Circular array of 300 buckets indexedts % 300, each(stored_ts, count)—hitis O(1),getHitsis O(300). -
Burst then quiet — the deque’s weak spot. 1M hits at ts=100, then
getHits(401)must popleft all 1M in one call. P99 latency suffers. The bucket design caps work per call regardless of traffic shape. -
Bucket staleness check is mandatory.
bucket[ts % 300]may hold a hit from 300+ seconds ago. On ahit, ifbucket[i].timestamp != ts, overwrite (don’t increment). OngetHits, skip buckets wherestored_ts <= ts - 300. -
Test the boundary.
getHits(300)should still seehit(1).getHits(301)should not. Off-by-one on<vs<=is the dominant bug.
If stuck: see solution.py.