progress

~/problems / Streams & durability / Rolling windows and rate counters

Page views in the last five minutes

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

A blog dashboard shows "views in the last 5 minutes". Servers report views in batches: one report can carry many views from the same second.

Build ViewCounter():

  • record(t: int, count: int) -> None: count views at second t.
  • total(t: int) -> int: views with t - 300 < time <= t. A view exactly 300 seconds old no longer counts.

t never decreases, and reports can share a second.

v = ViewCounter()
v.record(1, 5)
v.record(1, 2)
v.record(100, 10)
v.total(100)    # 17
v.total(300)    # 17   (the views at 1 are 299 seconds old)
v.total(301)    # 10   (the views at 1 are now 300 seconds old: gone)
v.total(400)    # 0
v.record(1000, 3)
v.total(1000)   # 3

1 <= count <= 1,000,000, so store reports, not single views; 0 <= t <= 10^9; totals can exceed 2^31.

⭐ Bonus: a speed test with 330,000 calls earns a star at O(1) amortized per call (O(1) on average over many calls, even if one call now and then does more), with memory that doesn't grow with the number of reports.

Show hint

only 300 distinct seconds matter at once: keep one record per second and update a running sum as old seconds fall out.

Topic: Rolling windows and rate counters. QPS over the last N seconds, hit counters, rate limiters.

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