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:countviews at secondt.total(t: int) -> int: views witht - 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.