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 == 0 logs a single incoming hit at timestamp.
  • kind == 1 requests 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:

  1. Sequential visibility: A query only counts hit events (kind == 0) that appear before that query in operations. When multiple hits and queries share an identical timestamp, their position in operations determines which hits have already been logged.
  2. Half-open 300-second window: For a query at time t, any earlier hit with timestamp h satisfying t - 300 < h <= t is counted once. A hit recorded at t - 300 is 300 seconds old and is not counted.
  3. Output list: Return a list containing one integer count per query (kind == 1), in the order those queries appear. Return [] when operations contains 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 at 10, the hit at 45, and the hit at 309 (4 total).
    • At t = 310, the interval shifts to (10, 310], expiring both hits at 10 and leaving 45 and 309 (2 total).
    • At t = 345, the interval (45, 345] expires 45, leaving only 309 (1 total).

Example 2

  • Input: operations = [[1, 20], [0, 20], [0, 20], [1, 20], [0, 20]]
  • Output: [0, 2]
  • Explanation: The first query at t = 20 precedes every hit, yielding 0. Two hits are then logged at t = 20, so the second query yields 2; the trailing hit at t = 20 comes 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 operations has length 2: [kind, timestamp] with kind in {0, 1} and 0 <= timestamp <= 10^9.
  • operations[i][1] <= operations[i + 1][1] for all 0 <= i < len(operations) - 1.

Step-by-step walkthrough

  1. Understand the event stream and boundary rules

    We process a list of [kind, timestamp] events sorted in nondecreasing order of timestamp:

    • kind == 0 logs one hit at timestamp.
    • kind == 1 queries the number of active hits in the trailing 300-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:

    1. Half-open interval (t - 300, t]: The left endpoint t - 300 is excluded while the right endpoint t is included. At query time t, a hit from t - 299 is 299 seconds old (counted), whereas a hit from t - 300 is 300 seconds old (expired).
    2. Sequential order within the same second: A query at t = 20 only counts hits that appeared before it in operations, never hits listed after it at t = 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 hits
    
  2. Why 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 whenever t - 300 < h <= t.

    Why does that time out when len(operations) reaches 200,000? If 100,000 hit events are followed by 100,000 query events, every single query re-checks all 100,000 hits—performing 100,000 * 100,000 = 10^10 comparisons even though back-to-back queries inspect almost the exact same active window.

  3. Key insight: expired hits never become valid again

    Because operations arrive in nondecreasing timestamp order (t_next >= t_now), the lower cutoff t - 300 never moves backward. Once an old hit falls on or to the left of t - 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]                           back
    

    Python's collections.deque supports both append (at the back) and popleft (from the front) in O(1) constant time. By contrast, calling pop(0) on a standard Python list shifts every remaining element one slot left, degrading n front removals to O(n^2) total work.

  4. Evict expired hits and handle each operation

    For each [kind, timestamp] entry, we execute two short phases in order:

    1. Evict expired hits: Compute cutoff = timestamp - 300. While the oldest surviving hit hits[0] satisfies hits[0] <= cutoff, pop it from the front. Using <= (rather than <) discards hits sitting right on the excluded left boundary timestamp - 300.
    2. Record or answer: If kind == 0, append timestamp to the back of hits. Otherwise (kind == 1), every timestamp left in hits satisfies t - 300 < h <= t and appeared earlier in operations, so len(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
    
  5. 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)
    
  6. 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 to hits once and popped by popleft() at most once across all n events, while len(hits) and appending to answers each cost O(1) time.
  • Space: O(w + q) (O(n) worst-case). Evicting expired entries on every event bounds hits to the w hits within the latest 300 seconds, and answers stores one integer for each of the q queries.

Edge cases

  • Empty input [] or hits without queries (Example 3): Zero query entries execute, cleanly returning [].
  • Queries before any hit: hits starts empty, so len(hits) returns 0.
  • Exact 300-second boundary (t = 0 and t = 300): A hit at 0 has 0 <= -1 false at t = 299 (counted) and 0 <= 0 true at t = 300 (evicted).
  • Hits and queries sharing the exact same second (Example 2): Sequential processing ensures [1, 20] before [0, 20] reports 0, while [1, 20] after two [0, 20] entries reports 2.
  • High-volume burst in one second: Duplicate timestamps are pushed individually so len(hits) counts every hit, and 300 seconds later the while loop evicts all of them together.
  • Large timestamp jump (such as 1 to 10^9): One while loop drains hits completely; since each item is popped only once in its lifetime, overall runtime stays O(n).

Common mistakes

  • Writing < instead of <= in the eviction check: Using hits[0] < timestamp - 300 retains hits from t - 300, turning the half-open window (t - 300, t] into [t - 300, t] and returning 4 instead of 2 at t = 310 in Example 1.
  • Pre-grouping operations by timestamp: Summing all hits at second 20 before answering queries at second 20 loses sequential order and breaks Example 2.
  • Using list.pop(0) instead of deque.popleft(): Front deletion on a Python list costs O(k) for length k, turning 200,000 streaming hits into O(n^2) work.
  • Evicting only on queries when memory matters: Running the eviction loop on every event yields identical query results while keeping hits bounded to 300 seconds even during long stretches with zero queries.

Alternative approaches

  • Append-only list with binary search: Append each hit timestamp to a sorted list and answer each query via binary search—repeatedly halving the list with bisect.bisect_right(hits, timestamp - 300) to locate the first hit strictly greater than timestamp - 300 in O(log n) time. Simple and able to answer historical queries, at the cost of O(n log n) runtime and retaining all past hits in memory.
  • Fixed-size circular buffer of 300 one-second buckets: Maintain times[300] and counts[300] indexed by timestamp % 300, a circular buffer—a fixed-length array whose index wraps around with modulo arithmetic so new seconds overwrite slots from 300+ seconds ago. Logging a hit resets the slot when times[slot] != timestamp and increments counts[slot] in O(1) time; querying sums counts[i] across all 300 slots where times[i] > timestamp - 300 in O(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 the deque alongside a running integer active_total. When a hit arrives at the same timestamp as hits[-1][0], simply increment hits[-1][1] and active_total; when popping an expired [old_ts, old_count] from the front, subtract old_count from active_total. Because (t - 300, t] covers at most 300 distinct integer seconds, the deque never exceeds 300 entries regardless of burst size.
  • How would your data structure change if hit events could arrive slightly out of chronological order? A plain FIFO deque no longer stays sorted if a delayed hit arrives with an older timestamp than hits[-1]. If queries still advance monotonically and hit delays stay under 300 seconds, the 300-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 in O(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 the 300 slots 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 around t - 300.

Follow-up questions

Similar questions

More Vercel interview questions

All 5 Vercel questions →