progress

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

Events in the last N seconds

On a phone? Coding is easier on a laptop: email this problem to yourself . Meanwhile: quiz this topic or fight a boss.

easy basics ~10 min

Events arrive at whole-number seconds times, oldest first (several can share a second). After each one, a dashboard shows how many events so far are in the last window seconds: times t with now - window < t <= now, where now is the new event's time. An event exactly window seconds old has dropped out.

Write recent_counts(times: list[int], window: int) -> list[int] that returns the number shown after each event.

recent_counts([1, 1, 5, 10, 11, 15], 10)   # [1, 2, 3, 4, 3, 3]
# at 10 the events at 1 are 9 seconds old: still in
# at 11 they're 10 seconds old: out
recent_counts([], 5)                       # []

Constraints: up to 2 * 10^5 events; 1 <= window <= 10^9; times are in [0, 10^9]. ⭐ Bonus: one test puts 200,000 events in one window, where counting back each time is too slow.

Show hint

keep start, the index of the oldest event still in the window. Each new event only ever pushes start forward.

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