Thread-Safe 300-Second Sliding Hit Counter

Medium · Software Engineering Fundamentals · Software Engineer · Onsite

Problem Statement

Build a thread-safe HitCounter class that counts incoming events within a trailing 300-second (five-minute) lookback window, along with the replay driver hit_counter_operations(operations, arguments).

class HitCounter:
    def __init__(self) -> None: ...
    def hit(self, timestamp: int) -> None: ...
    def getHits(self, timestamp: int) -> int: ...


def hit_counter_operations(
    operations: List[str], arguments: List[List[int]]
) -> List[Optional[int]]:

Operations & Rules

  • hit(timestamp) logs a single event at integer second timestamp and returns None. Sequential hit invocations arrive in monotonic non-decreasing timestamp order (t_1 <= t_2 <= ...), and arbitrarily many events may share the same second.
  • getHits(timestamp) returns how many logged events have timestamps inside the closed interval [timestamp - 299, timestamp]:
    • Events logged at timestamp - 300 or earlier fall outside the 300-second window and are excluded.
    • A getHits(timestamp) query may specify a timestamp earlier than already-logged events; any event logged strictly after timestamp must also be excluded.
  • HitCounter must remain race-free when multiple threads invoke hit and getHits concurrently, and must stay fast under heavy bursts of same-second events and wide gaps between timestamps.
  • hit_counter_operations(operations, arguments) starts with a fresh HitCounter, runs each command operations[i] ("hit" or "getHits", plus "HitCounter" to reset) using arguments[i], and returns the collected outputs (None for "hit" / "HitCounter", and the integer count for "getHits").

Examples

Example 1

Input:
  operations = ["hit", "hit", "hit", "getHits", "hit", "getHits", "getHits"]
  arguments  = [[5], [5], [12], [20], [304], [304], [305]]
Output: [None, None, None, 3, None, 4, 2]

Walk-through:

  • Two events land at second 5 and one lands at second 12.
  • getHits(20) inspects [-279, 20], counting all 3 events (5, 5, 12).
  • Another event lands at second 304.
  • getHits(304) inspects [5, 304]; second 5 sits right on the inclusive left boundary, so all 4 events count.
  • getHits(305) inspects [6, 305]; both events at second 5 have aged out, leaving the 2 events at seconds 12 and 304.

Example 2

Input:
  operations = ["getHits", "hit", "hit", "getHits", "getHits", "getHits"]
  arguments  = [[50], [100], [450], [80], [250], [450]]
Output: [0, None, None, 0, 1, 1]

Walk-through:

  • getHits(50) runs before any event is logged and returns 0.
  • Events are logged at seconds 100 and 450.
  • getHits(80) queries a timestamp prior to both logged events (100 and 450), returning 0.
  • getHits(250) inspects [-49, 250], which includes 100 and ignores the later event at 450, returning 1.
  • getHits(450) inspects [151, 450], where 100 has already expired and only 450 remains, returning 1.

Constraints

  • 1 <= timestamp <= 2 * 10^9
  • 0 <= len(operations) == len(arguments) <= 2 * 10^5
  • Sequential hit calls satisfy timestamp_prev <= timestamp_curr
  • getHits(timestamp) may query any valid timestamp 1 <= timestamp <= 2 * 10^9, including timestamps earlier than previously logged hit calls

Step-by-step walkthrough

  1. Understand the operations and the 300-second window

    We need a thread-safe HitCounter supporting two methods:

    • hit(timestamp) logs one event at integer second timestamp. Sequential hit calls never move backward in time (t_1 <= t_2 <= ...), and many events may land on the exact same second.
    • getHits(timestamp) counts how many logged events fall inside the closed 300-second interval [timestamp - 299, timestamp].

    Check the endpoints carefully. From second 5 through second 304 inclusive there are 304 - 5 + 1 = 300 seconds:

    getHits(304) -> window is [5, 304]   -> events at t=5 ARE included
    getHits(305) -> window is [6, 305]   -> events at t=5 happened 300s ago, so they are EXCLUDED
    

    Notice a subtle rule illustrated in Example 2 (hit(100), hit(450), getHits(80) -> 0): although hit timestamps are monotonic, getHits(timestamp) can query a point in time earlier than already-logged hits. Events recorded strictly after the query timestamp must not be counted.

  2. Why a raw event list or a 300-bucket ring buffer falls short

    A brute-force counter appends every event timestamp to a list and scans the entire list on each getHits call:

    def brute_get_hits(hits: List[int], timestamp: int) -> int:
        count = 0
        for hit_time in hits:
            if timestamp - 299 <= hit_time <= timestamp:
                count += 1
        return count
    

    Under heavy traffic—say 10 million events—every getHits query scans 10 million integers (O(H) time and O(H) memory for H events).

    What about a 300-bucket ring buffer (bucket = timestamp % 300)? That works only when queries never look backward in time, because wrapping around overwrites older history permanently:

    1. hit(5)       -> bucket 5 stores (time=5,   count=1)
    2. hit(305)     -> bucket 5 overwritten with (time=305, count=1)
    3. getHits(120) -> window [-179, 120] should still count the event at t=5 (answer: 1),
                       but bucket 5 now holds time=305, so the ring buffer returns 0!
    

    We want a design that answers arbitrary query timestamps accurately while still collapsing same-second bursts in O(1) time.

  3. Key idea: cumulative prefix sums per distinct second + binary search

    Rather than storing one entry per event, we coalesce same-second events and maintain prefix sums (running cumulative totals from the start):

    • _times: strictly increasing list of distinct seconds that received at least one event.
    • _prefix_counts: _prefix_counts[i] holds the cumulative number of events logged at time <= _times[i].

    Why do cumulative totals make range counting effortless? For integer seconds, the number of events inside [timestamp - 299, timestamp] equals all events at or before timestamp minus all events at or before timestamp - 300:

    Timeline:   ... | t - 300 | t - 299 ...         t | t + 1 ...
                <-------------+----------------------->
                 hits <= t-300     window [t-299, t]
                <------------------------------------->
                              hits <= t
    
    hits in [t - 299, t] = (hits <= t) - (hits <= t - 300)
    

    Because _times is strictly sorted, we can look up (hits <= x) for any integer x in O(log D) time via binary search (D = number of distinct seconds with events).

  4. Log events in O(1) time under a mutex

    Because hit timestamps arrive monotonically, each incoming event either matches the final second in _times (_times[-1] == timestamp) or introduces a strictly larger second at the tail:

    • Same second: increment _prefix_counts[-1] in place. Zero extra memory is allocated, even when thousands of events burst in one second.
    • New second: read the previous cumulative total (0 if empty, else _prefix_counts[-1]), append timestamp to _times, and append previous_total + 1 to _prefix_counts.

    To keep HitCounter thread-safe, we guard _times and _prefix_counts with threading.Lock(). Without a mutex, two threads incrementing _prefix_counts[-1] concurrently could suffer a lost update, or a reader could observe _times right after an append before _prefix_counts is updated.

    class HitCounter:
        """Thread-safe counter returning events within [timestamp - 299, timestamp]."""
    
        def __init__(self) -> None:
            # _times: strictly increasing list of distinct event seconds, e.g. [5, 12, 304]
            self._times: List[int] = []
            # _prefix_counts: cumulative totals where _prefix_counts[i] = total hits at time <= _times[i]
            self._prefix_counts: List[int] = []
            # _lock: mutex keeping _times and _prefix_counts synchronized across threads
            self._lock = threading.Lock()
    
        def hit(self, timestamp: int) -> None:
            with self._lock:
                # Phase 1: Coalesce same-second bursts into one slot so memory scales
                # with distinct active seconds rather than raw event count.
                if self._times and self._times[-1] == timestamp:
                    self._prefix_counts[-1] += 1
                else:
                    # Phase 2: Hit timestamps arrive monotonically, so any new second
                    # is strictly greater than _times[-1] and appends straight to the end.
                    if self._prefix_counts:
                        previous_total = self._prefix_counts[-1]
                    else:
                        previous_total = 0
                    self._times.append(timestamp)
                    self._prefix_counts.append(previous_total + 1)
    
  5. Answer window queries in O(log D) with `bisect_right`

    To evaluate _count_hits_up_to(x), we find how many entries in _times satisfy <= x using bisect_right(_times, x):

    Suppose _times         = [5, 12, 304]
            _prefix_counts = [2,  3,   4]
    
    Query x = 4:    bisect_right -> 0  (no timestamps <= 4)        -> count is 0
    Query x = 5:    bisect_right -> 1  (_times[0] = 5 is <= 5)     -> _prefix_counts[0] = 2
    Query x = 20:   bisect_right -> 2  (_times[1] = 12 is <= 20)   -> _prefix_counts[1] = 3
    Query x = 305:  bisect_right -> 3  (_times[2] = 304 is <= 305) -> _prefix_counts[2] = 4
    

    Inside getHits(timestamp), holding self._lock ensures both binary searches read a consistent pair of arrays before returning _count_hits_up_to(timestamp) - _count_hits_up_to(timestamp - 300).

        def _count_hits_up_to(self, timestamp: int) -> int:
            """Return cumulative hits logged at time <= timestamp. Caller must hold _lock."""
            # bisect_right returns how many stored timestamps are <= timestamp.
            # When insertion_index == 0, every stored event occurred strictly after `timestamp`.
            insertion_index = bisect_right(self._times, timestamp)
            if insertion_index == 0:
                return 0
            return self._prefix_counts[insertion_index - 1]
    
        def getHits(self, timestamp: int) -> int:
            with self._lock:
                # For integer seconds, events in [timestamp - 299, timestamp] equal
                # (events with time <= timestamp) minus (events with time <= timestamp - 300).
                hits_up_to_query = self._count_hits_up_to(timestamp)
                hits_before_window = self._count_hits_up_to(timestamp - WINDOW_SECONDS)
                return hits_up_to_query - hits_before_window
    
  6. Implement the replay driver and trace both examples

    hit_counter_operations instantiates HitCounter, steps through operations and arguments in lockstep, and records None for "hit" and the integer count for "getHits".

    Let's trace Examples 1 and 2 to confirm every boundary:

    Example 1:
      hit(5), hit(5), hit(12) -> _times = [5, 12], _prefix_counts = [2, 3]
      getHits(20)             -> up_to(20) - up_to(-280) = 3 - 0 = 3
      hit(304)                -> _times = [5, 12, 304], _prefix_counts = [2, 3, 4]
      getHits(304)            -> up_to(304) - up_to(4)   = 4 - 0 = 4
      getHits(305)            -> up_to(305) - up_to(5)   = 4 - 2 = 2  (both hits at t=5 aged out!)
    
    Example 2:
      getHits(50)             -> up_to(50) - up_to(-250) = 0 - 0 = 0  (empty counter)
      hit(100), hit(450)      -> _times = [100, 450], _prefix_counts = [1, 2]
      getHits(80)             -> up_to(80) - up_to(-220) = 0 - 0 = 0  (later hits ignored!)
      getHits(250)            -> up_to(250) - up_to(-50) = 1 - 0 = 1  (only t=100 counted)
      getHits(450)            -> up_to(450) - up_to(150) = 2 - 1 = 1  (t=100 expired, t=450 counted)
    
  7. Complete solution

    from typing import Any, Dict, List, Optional, Set, Tuple
    import threading
    from bisect import bisect_right
    
    # Lookback window width in seconds (5 minutes = 300 seconds).
    WINDOW_SECONDS = 300
    
    
    class HitCounter:
        """Thread-safe counter returning events within [timestamp - 299, timestamp]."""
    
        def __init__(self) -> None:
            # _times: strictly increasing list of distinct event seconds, e.g. [5, 12, 304]
            self._times: List[int] = []
            # _prefix_counts: cumulative totals where _prefix_counts[i] = total hits at time <= _times[i]
            self._prefix_counts: List[int] = []
            # _lock: mutex keeping _times and _prefix_counts synchronized across threads
            self._lock = threading.Lock()
    
        def hit(self, timestamp: int) -> None:
            with self._lock:
                # Phase 1: Coalesce same-second bursts into one slot so memory scales
                # with distinct active seconds rather than raw event count.
                if self._times and self._times[-1] == timestamp:
                    self._prefix_counts[-1] += 1
                else:
                    # Phase 2: Hit timestamps arrive monotonically, so any new second
                    # is strictly greater than _times[-1] and appends straight to the end.
                    if self._prefix_counts:
                        previous_total = self._prefix_counts[-1]
                    else:
                        previous_total = 0
                    self._times.append(timestamp)
                    self._prefix_counts.append(previous_total + 1)
    
        def _count_hits_up_to(self, timestamp: int) -> int:
            """Return cumulative hits logged at time <= timestamp. Caller must hold _lock."""
            # bisect_right returns how many stored timestamps are <= timestamp.
            # When insertion_index == 0, every stored event occurred strictly after `timestamp`.
            insertion_index = bisect_right(self._times, timestamp)
            if insertion_index == 0:
                return 0
            return self._prefix_counts[insertion_index - 1]
    
        def getHits(self, timestamp: int) -> int:
            with self._lock:
                # For integer seconds, events in [timestamp - 299, timestamp] equal
                # (events with time <= timestamp) minus (events with time <= timestamp - 300).
                hits_up_to_query = self._count_hits_up_to(timestamp)
                hits_before_window = self._count_hits_up_to(timestamp - WINDOW_SECONDS)
                return hits_up_to_query - hits_before_window
    
    
    def hit_counter_operations(
        operations: List[str], arguments: List[List[int]]
    ) -> List[Optional[int]]:
        """Replay a sequence of HitCounter operations and collect their outputs."""
        counter = HitCounter()
        results: List[Optional[int]] = []
    
        for op, args in zip(operations, arguments):
            if op == "hit":
                counter.hit(args[0])
                results.append(None)
            elif op == "getHits":
                results.append(counter.getHits(args[0]))
            elif op == "HitCounter":
                # Support explicit constructor entries if a caller resets the instance.
                counter = HitCounter()
                results.append(None)
            else:
                raise ValueError(f"unknown operation: {op}")
    
        return results
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Think of counting recent events like reading a car's odometer: if the odometer showed 120 miles five minutes ago and shows 155 miles right now, you immediately know you drove 155 - 120 = 35 miles over the past five minutes without replaying every mile marker. We use that exact principle via prefix sums (cumulative running totals of all events logged up through each distinct second). Because hit calls arrive in monotonic non-decreasing timestamp order, _times stays sorted automatically, letting us read the cumulative total at any second with binary search (repeatedly halving the sorted array to locate the rightmost timestamp at or below our target in logarithmic time).

Why not append every hit to a plain list or use a 300-slot ring buffer? Appending every event separately forces getHits to scan the entire history on every query, which boggs down under heavy traffic. A 300-slot circular buffer (a fixed-length array indexed by timestamp % 300 that overwrites older buckets as time advances) uses constant space, but overwriting buckets destroys prior history—so if getHits queries an earlier timestamp after newer hits have arrived (such as hit(5), hit(305), getHits(120)), the overwritten bucket mistakenly reports 0 instead of 1. Coalescing per distinct second with prefix sums absorbs thousands of same-second events into a single slot AND answers queries at any timestamp accurately.

Here is a step-by-step trace using Example 1 (hit(5), hit(5), hit(12), hit(304)):

Recorded state:
  _times         = [5, 12, 304]
  _prefix_counts = [2,  3,   4]

Query getHits(304) -> window [5, 304]:
  hits <= 304 is 4 (_times[2] = 304)
  hits <= 4   is 0 (no timestamp <= 4)
  answer = 4 - 0 = 4

Query getHits(305) -> window [6, 305]:
  hits <= 305 is 4 (_times[2] = 304)
  hits <= 5   is 2 (_times[0] = 5)
  answer = 4 - 2 = 2  (both events at t=5 drop out cleanly!)

Complexity

Let H be the total number of hit calls, D (D <= H) be the number of distinct seconds with at least one event, and N be len(operations).

  • hit(timestamp): O(1) amortized time. Under the mutex (a mutual-exclusion lock allowing only one thread inside the critical section at once), we inspect _times[-1] and either increment _prefix_counts[-1] in place or append to two Python lists (O(1) amortized time, meaning occasional internal list growth averages out to constant work per append).
  • getHits(timestamp): O(log D) time. While holding the mutex, we run bisect_right twice over the D sorted entries in _times—once at timestamp and once at timestamp - 300—and subtract the two prefix totals.
  • hit_counter_operations: O(N log D) time across N commands, since each hit is O(1) amortized and each getHits is O(log D).
  • Space: O(D). We keep two integers per distinct active second (_times[i] and _prefix_counts[i]); arbitrarily large bursts within the same second share one slot with zero extra memory.

Edge cases

  • Bursts of hits in a single second: self._times[-1] == timestamp folds all of them into _prefix_counts[-1], so they enter and expire from the 300-second window together.
  • Inclusive vs. exclusive window edges (t + 299 vs t + 300): Events at t = 5 count at getHits(304) (304 - 300 = 4 < 5) and expire at getHits(305) (305 - 300 = 5 subtracts _prefix_counts[0]).
  • Queries before any hits or before all logged timestamps (Example 2): Both bisect_right lookups return 0, producing 0 - 0 = 0 without counting future events.
  • Historical queries after newer hits (hit(5), hit(305), getHits(120)): _count_hits_up_to(120) stops at t = 5 and ignores t = 305, returning 1.
  • Wide timestamp jumps up to 2 * 10^9: Quiet periods allocate zero slots, and negative cutoffs such as 20 - 300 = -280 cleanly return 0 from bisect_right.

Common mistakes

  • Off-by-one cutoff (timestamp - 299 instead of timestamp - 300): Because [timestamp - 299, timestamp] spans 300 inclusive integer seconds, events at timestamp - 299 belong inside the count; you must subtract events at or before timestamp - 300.
  • Including future hits when getHits(t) queries t earlier than logged events: A naive queue that only pops timestamps <= t - 300 and returns queue size fails Example 2 (hit(100), hit(450), getHits(80)), returning 2 instead of 0.
  • Destructively discarding old entries when historical queries occur: Popping from a deque or overwriting modulo-300 slots loses counts needed if a later getHits queries an earlier timestamp.
  • Relying on Python's GIL instead of an explicit lock: Even under CPython's Global Interpreter Lock, self._prefix_counts[-1] += 1 executes multiple bytecode instructions where threads can interleave and drop increments, or observe mismatched lengths between _times and _prefix_counts.

Alternative approaches

  • Modulo-300 ring buffer (only when getHits is also monotonic): Keep slot_time = [0] * 300 and slot_count = [0] * 300 indexed by t % 300, resetting slot_count[idx] = 1 when slot_time[idx] != t and summing buckets with t - 300 < slot_time[i] <= t. That uses O(1) memory (300 integers), at the cost of losing counts whenever timestamps advance past 300 seconds and an older timestamp is queried.
  • Monotonic deque with running total (strictly non-decreasing hit and getHits): Store [second, count] pairs in collections.deque and pop expired front pairs <= t - 300 while subtracting from a running sum, giving O(1) amortized hit and getHits when queries never look backward.

Follow-up questions

  • How can you make the counter safe and scalable when many worker threads invoke hit and getHits concurrently? Wrapping hit and getHits in threading.Lock guarantees atomic updates and consistent reads across _times and _prefix_counts. Under extreme write contention across many cores, apply lock striping (partitioning into S independent shard counters—say S = 16—where each writer hashes its thread ID to update one shard and getHits sums across all S shards). In real systems where threads read wall-clock timestamps before acquiring a lock, timestamps can arrive slightly out of order by a millisecond or two; handling small reorderings cleanly simply walks backward a few tail entries in _times to increment the matching second.
  • What happens to memory consumption if the lookback window expands to 24 hours, and what trade-offs could keep memory bounded? Changing WINDOW_SECONDS to 86,400 requires zero structural changes to prefix sums, and one full day of active seconds (86,400 integers) takes well under 2 MB. Over weeks of continuous uptime, if historical queries older than 24 hours are not needed, you can periodically compact entries older than latest_time - 86,400 into a base offset or use an 86,400-slot ring buffer maintained with a running window sum; if sub-second boundary precision is unnecessary, coarsening into 1,440 one-minute buckets shrinks memory by 60x.
  • How would you redesign this counter when events land across a fleet of stateless servers rather than a single process? Have each application host accumulate per-second counts locally in memory and flush compact (second, local_count) deltas once per second to a shared store such as Redis (INCRBY on key hits:<second> with a 6-minute TTL) or a streaming pipeline. Pre-aggregating locally collapses thousands of requests per second per host into a single network write. Be sure to mention NTP clock synchronization (using server ingestion time rather than client-supplied timestamps) and the ~1-second flush latency trade-off.

Follow-up questions

Similar questions

More Apple interview questions

All 177 Apple questions →