Five-Minute Sliding Hit Counter
Medium · Coding & Algorithms · Software Engineer · Technical Screen
Problem Statement
Build an event-stream counter that tracks traffic over a trailing five-minute (300-second) window.
You are given a sequence operations where each element is a two-integer list [kind, timestamp] with timestamp measured in whole seconds and sorted in nondecreasing chronological order:
kind == 0logs a single incoming hit attimestamp.kind == 1requests the number of logged hits that fall within the half-open time range(timestamp - 300, timestamp].
def count_recent_hits(operations: List[List[int]]) -> List[int]:
Apply these exact visibility and boundary rules:
- Sequential visibility: A query only counts hit events (
kind == 0) that appear before that query inoperations. When multiple hits and queries share an identicaltimestamp, their position inoperationsdetermines which hits have already been logged. - Half-open
300-second window: For a query at timet, any earlier hit with timestamphsatisfyingt - 300 < h <= tis counted once. A hit recorded att - 300is300seconds old and is not counted. - Output list: Return a list containing one integer count per query (
kind == 1), in the order those queries appear. Return[]whenoperationscontains no queries.
Examples
Example 1
- Input:
operations = [[0, 10], [0, 10], [0, 45], [0, 309], [1, 309], [1, 310], [1, 345]] - Output:
[4, 2, 1] - Explanation:
- At
t = 309, the active interval(9, 309]includes both hits at10, the hit at45, and the hit at309(4total). - At
t = 310, the interval shifts to(10, 310], expiring both hits at10and leaving45and309(2total). - At
t = 345, the interval(45, 345]expires45, leaving only309(1total).
- At
Example 2
- Input:
operations = [[1, 20], [0, 20], [0, 20], [1, 20], [0, 20]] - Output:
[0, 2] - Explanation: The first query at
t = 20precedes every hit, yielding0. Two hits are then logged att = 20, so the second query yields2; the trailing hit att = 20comes after that query and does not affect its answer.
Example 3
- Input:
operations = [[0, 50], [0, 120]] - Output:
[] - Explanation: Because no query entries (
kind == 1) appear in the stream, the result is an empty list.
Constraints
0 <= len(operations) <= 200,000- Each element of
operationshas length2:[kind, timestamp]withkindin{0, 1}and0 <= timestamp <= 10^9. operations[i][1] <= operations[i + 1][1]for all0 <= i < len(operations) - 1.
Step-by-step walkthrough
Understand the event stream and boundary rules
We process a list of
[kind, timestamp]events sorted in nondecreasing order oftimestamp:kind == 0logs one hit attimestamp.kind == 1queries the number of active hits in the trailing300-second window(timestamp - 300, timestamp].
We return a list with one integer answer per query, preserving query order.
Two boundary details govern every edge case:
- Half-open interval
(t - 300, t]: The left endpointt - 300is excluded while the right endpointtis included. At query timet, a hit fromt - 299is299seconds old (counted), whereas a hit fromt - 300is300seconds old (expired). - Sequential order within the same second: A query at
t = 20only counts hits that appeared before it inoperations, never hits listed after it att = 20.
Query at t = 309 -> window is (9, 309]: 2 hits at 10 hit at 45 hit at 309 vv v v (------10--------------45-----------------------309] 9 (excluded) 309 (included) -> 4 hits Query at t = 310 -> window advances to (10, 310]: 2 hits at 10 hit at 45 hit at 309 xx v v (---------------45-----------------------309-] 10 (now excluded!) 310 (included) -> 2 hitsWhy rescanning earlier hits is too slow
A brute-force solution stops at each query
[1, t], loops back over every preceding entry[0, h], and increments a counter whenevert - 300 < h <= t.Why does that time out when
len(operations)reaches200,000? If100,000hit events are followed by100,000query events, every single query re-checks all100,000hits—performing100,000 * 100,000 = 10^10comparisons even though back-to-back queries inspect almost the exact same active window.Key insight: expired hits never become valid again
Because
operationsarrive in nondecreasing timestamp order (t_next >= t_now), the lower cutofft - 300never moves backward. Once an old hit falls on or to the left oft - 300, it can never fall inside any subsequent query's window either.That monotonicity lets us maintain only the still-active hit timestamps inside a first-in, first-out (FIFO) queue—a line where newly logged timestamps join at the back and expired timestamps leave from the front:
Oldest hits leave here Newest hits enter here v v popleft() <-- [ t = 10 | t = 10 | t = 45 | t = 309 ] <-- append(timestamp) front: hits[0] backPython's
collections.dequesupports bothappend(at the back) andpopleft(from the front) inO(1)constant time. By contrast, callingpop(0)on a standard Pythonlistshifts every remaining element one slot left, degradingnfront removals toO(n^2)total work.Evict expired hits and handle each operation
For each
[kind, timestamp]entry, we execute two short phases in order:- Evict expired hits: Compute
cutoff = timestamp - 300. While the oldest surviving hithits[0]satisfieshits[0] <= cutoff, pop it from the front. Using<=(rather than<) discards hits sitting right on the excluded left boundarytimestamp - 300. - Record or answer: If
kind == 0, appendtimestampto the back ofhits. Otherwise (kind == 1), every timestamp left inhitssatisfiest - 300 < h <= tand appeared earlier inoperations, solen(hits)is our exact count.
WINDOW_SECONDS = 300 HIT_EVENT = 0 def count_recent_hits(operations: List[List[int]]) -> List[int]: # hits: FIFO queue of int timestamps still inside the window, e.g. deque([10, 10, 45, 309]) # Ordered oldest (front) to newest (back) because input timestamps never decrease. hits = deque() answers = [] for kind, timestamp in operations: # Phase 1 (Evict): drop hits that are 300 or more seconds old. # Use <= because a hit at (timestamp - 300) lies on the excluded left boundary. cutoff = timestamp - WINDOW_SECONDS while hits and hits[0] <= cutoff: hits.popleft() # Phase 2 (Record or Query): handling operations in input order ensures # a query at timestamp t only counts hits recorded earlier in the list. if kind == HIT_EVENT: hits.append(timestamp) else: answers.append(len(hits)) return answers- Evict expired hits: Compute
Trace Example 1 and Example 2 step by step
Example 1:
operations = [[0, 10], [0, 10], [0, 45], [0, 309], [1, 309], [1, 310], [1, 345]]Op cutoff Evicted hits after op answers ----------------------------------------------------------------- [0, 10] -290 none [10] [] [0, 10] -290 none [10, 10] [] [0, 45] -255 none [10, 10, 45] [] [0, 309] 9 none [10, 10, 45, 309] [] [1, 309] 9 none [10, 10, 45, 309] [4] (10 > 9, both 10s stay) [1, 310] 10 10, 10 [45, 309] [4, 2] (10 <= 10, both 10s popped!) [1, 345] 45 45 [309] [4, 2, 1] (45 <= 45, popped!)Example 2:
operations = [[1, 20], [0, 20], [0, 20], [1, 20], [0, 20]]Op cutoff hits after op answers ---------------------------------------------- [1, 20] -280 [] [0] (query precedes every hit) [0, 20] -280 [20] [0] [0, 20] -280 [20, 20] [0] [1, 20] -280 [20, 20] [0, 2] (sees 2 earlier hits) [0, 20] -280 [20, 20, 20] [0, 2] (trailing hit arrives after last query)Complete solution
from typing import Any, Dict, List, Optional, Set, Tuple from collections import deque # Five minutes equals 300 seconds; a query at t counts hits in (t - 300, t]. WINDOW_SECONDS = 300 HIT_EVENT = 0 def count_recent_hits(operations: List[List[int]]) -> List[int]: # hits: FIFO queue of int timestamps still inside the window, e.g. deque([10, 10, 45, 309]) # Ordered oldest (front) to newest (back) because input timestamps never decrease. hits = deque() answers = [] for kind, timestamp in operations: # Phase 1 (Evict): drop hits that are 300 or more seconds old. # Use <= because a hit at (timestamp - 300) lies on the excluded left boundary. cutoff = timestamp - WINDOW_SECONDS while hits and hits[0] <= cutoff: hits.popleft() # Phase 2 (Record or Query): handling operations in input order ensures # a query at timestamp t only counts hits recorded earlier in the list. if kind == HIT_EVENT: hits.append(timestamp) else: answers.append(len(hits)) return answers✅ Submit now — all tests should pass.
Intuition & how it works
Imagine a ticket tray at a turnstile: each time a visitor enters, an attendant drops a time-stamped slip at the back of the tray, and whenever someone asks for the five-minute traffic total, the attendant pulls any slips that are 300 or more seconds old off the front and reports how many slips remain. Because events arrive in nondecreasing chronological order, the 300-second range (t - 300, t] forms a sliding window—a fixed-width interval that only ever shifts forward in time. Keeping active hit timestamps in a double-ended queue (deque)—a first-in, first-out structure supporting O(1) appends at the back and O(1) removals from the front—places the oldest surviving hit right at hits[0] where we can test and evict it immediately.
Why do naive approaches struggle? Rescanning all earlier entries on each query does O(n^2) work (10^10 checks when 100,000 hits precede 100,000 queries) even though consecutive queries inspect nearly the exact same hits. Storing active hits in a plain Python list and calling list.pop(0) to drop expired timestamps also degrades to O(n^2), because removing element 0 shifts every remaining element one slot left in memory. With a deque, each hit enters once and leaves at most once in O(1) time.
Let's walk through Example 1 ([[0, 10], [0, 10], [0, 45], [0, 309], [1, 309], [1, 310], [1, 345]]):
1. [0, 10], [0, 10], [0, 45], [0, 309]:
cutoff <= 9 -> 10 > 9, nothing expires -> hits = [10, 10, 45, 309]
2. [1, 309] (query at 309): cutoff = 9 -> 10 > 9, keep all -> len(hits) = 4
3. [1, 310] (query at 310): cutoff = 10 -> pop both 10s (<= 10) -> hits = [45, 309], count = 2
4. [1, 345] (query at 345): cutoff = 45 -> pop 45 (<= 45) -> hits = [309], count = 1
Result: [4, 2, 1]
Complexity
Let n = len(operations), w be the peak number of hits active inside any 300-second window (w <= n), and q be the number of queries.
- Time:
O(n). By amortized analysis—totalling the work across the entire run rather than multiplying by the worst single step—each logged hit is appended tohitsonce and popped bypopleft()at most once across allnevents, whilelen(hits)and appending toanswerseach costO(1)time. - Space:
O(w + q)(O(n)worst-case). Evicting expired entries on every event boundshitsto thewhits within the latest300seconds, andanswersstores one integer for each of theqqueries.
Edge cases
- Empty input
[]or hits without queries (Example 3): Zero query entries execute, cleanly returning[]. - Queries before any hit:
hitsstarts empty, solen(hits)returns0. - Exact
300-second boundary (t = 0andt = 300): A hit at0has0 <= -1false att = 299(counted) and0 <= 0true att = 300(evicted). - Hits and queries sharing the exact same second (Example 2): Sequential processing ensures
[1, 20]before[0, 20]reports0, while[1, 20]after two[0, 20]entries reports2. - High-volume burst in one second: Duplicate timestamps are pushed individually so
len(hits)counts every hit, and300seconds later thewhileloop evicts all of them together. - Large timestamp jump (such as
1to10^9): Onewhileloop drainshitscompletely; since each item is popped only once in its lifetime, overall runtime staysO(n).
Common mistakes
- Writing
<instead of<=in the eviction check: Usinghits[0] < timestamp - 300retains hits fromt - 300, turning the half-open window(t - 300, t]into[t - 300, t]and returning4instead of2att = 310in Example 1. - Pre-grouping operations by timestamp: Summing all hits at second
20before answering queries at second20loses sequential order and breaks Example 2. - Using
list.pop(0)instead ofdeque.popleft(): Front deletion on a PythonlistcostsO(k)for lengthk, turning200,000streaming hits intoO(n^2)work. - Evicting only on queries when memory matters: Running the eviction loop on every event yields identical query results while keeping
hitsbounded to300seconds even during long stretches with zero queries.
Alternative approaches
- Append-only list with binary search: Append each hit timestamp to a sorted
listand answer each query via binary search—repeatedly halving the list withbisect.bisect_right(hits, timestamp - 300)to locate the first hit strictly greater thantimestamp - 300inO(log n)time. Simple and able to answer historical queries, at the cost ofO(n log n)runtime and retaining all past hits in memory. - Fixed-size circular buffer of
300one-second buckets: Maintaintimes[300]andcounts[300]indexed bytimestamp % 300, a circular buffer—a fixed-length array whose index wraps around with modulo arithmetic so new seconds overwrite slots from300+seconds ago. Logging a hit resets the slot whentimes[slot] != timestampand incrementscounts[slot]inO(1)time; querying sumscounts[i]across all300slots wheretimes[i] > timestamp - 300inO(300)(O(1)) time and constant memory.
Follow-up questions
- How can you bound memory to O(1) even when millions of hits arrive during the same second? Coalesce identical-second hits by storing
[timestamp, count_for_second]pairs in thedequealongside a running integeractive_total. When a hit arrives at the same timestamp ashits[-1][0], simply incrementhits[-1][1]andactive_total; when popping an expired[old_ts, old_count]from the front, subtractold_countfromactive_total. Because(t - 300, t]covers at most300distinct integer seconds, thedequenever exceeds300entries regardless of burst size. - How would your data structure change if hit events could arrive slightly out of chronological order? A plain FIFO
dequeno longer stays sorted if a delayed hit arrives with an older timestamp thanhits[-1]. If queries still advance monotonically and hit delays stay under300seconds, the300-bucket circular buffer (timestamp % 300) handles out-of-order hits directly because each hit lands in its exact second's bucket without overwriting newer seconds. If delays or queries can span arbitrary ranges, store timestamps in an order-statistic tree—a balanced binary search tree augmented with subtree counts so both out-of-order insertions and interval counts run inO(log n)time. - How would you adapt this design to count recent hits across multiple worker threads or distributed servers? Inside a multi-threaded process, give each worker thread its own lock-free or thread-local
300-slot per-second counter array so hot writes never contend on a shared mutex, and sum the300slots across threads at query time. Across distributed servers, each node aggregates per-second counts locally and flushes them to a shared store (or serves scatter-gather reads); the primary operational caveat is clock skew—small offsets between machines' wall clocks that can shift counts slightly right aroundt - 300.
Follow-up questions
- How can you bound memory to O(1) even when millions of hits arrive during the same second?
- How would your data structure change if hit events could arrive slightly out of chronological order?
- How would you adapt this design to count recent hits across multiple worker threads or distributed servers?
Similar questions
- Bottom-Up Tree Height Layers
- Query Recent Time-Series Metrics by Name and Tag Subset
- Real-Time Multi-User Document Editing Service
- Scalable URL Shortening and Edge Redirect System
- 2D Max Pooling with Source Coordinates
- Time-Limited Credit Ledger