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 secondtimestampand returnsNone. Sequentialhitinvocations 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 - 300or earlier fall outside the 300-second window and are excluded. - A
getHits(timestamp)query may specify atimestampearlier than already-logged events; any event logged strictly aftertimestampmust also be excluded.
- Events logged at
HitCountermust remain race-free when multiple threads invokehitandgetHitsconcurrently, and must stay fast under heavy bursts of same-second events and wide gaps between timestamps.hit_counter_operations(operations, arguments)starts with a freshHitCounter, runs each commandoperations[i]("hit"or"getHits", plus"HitCounter"to reset) usingarguments[i], and returns the collected outputs (Nonefor"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
5and one lands at second12. getHits(20)inspects[-279, 20], counting all3events (5, 5, 12).- Another event lands at second
304. getHits(304)inspects[5, 304]; second5sits right on the inclusive left boundary, so all4events count.getHits(305)inspects[6, 305]; both events at second5have aged out, leaving the2events at seconds12and304.
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 returns0.- Events are logged at seconds
100and450. getHits(80)queries a timestamp prior to both logged events (100and450), returning0.getHits(250)inspects[-49, 250], which includes100and ignores the later event at450, returning1.getHits(450)inspects[151, 450], where100has already expired and only450remains, returning1.
Constraints
1 <= timestamp <= 2 * 10^90 <= len(operations) == len(arguments) <= 2 * 10^5- Sequential
hitcalls satisfytimestamp_prev <= timestamp_curr getHits(timestamp)may query any valid timestamp1 <= timestamp <= 2 * 10^9, including timestamps earlier than previously loggedhitcalls
Step-by-step walkthrough
Understand the operations and the 300-second window
We need a thread-safe
HitCountersupporting two methods:hit(timestamp)logs one event at integer secondtimestamp. Sequentialhitcalls 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
5through second304inclusive there are304 - 5 + 1 = 300seconds: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 EXCLUDEDNotice a subtle rule illustrated in Example 2 (
hit(100),hit(450),getHits(80) -> 0): althoughhittimestamps are monotonic,getHits(timestamp)can query a point in time earlier than already-logged hits. Events recorded strictly after the querytimestampmust not be counted.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
getHitscall: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 countUnder heavy traffic—say 10 million events—every
getHitsquery scans 10 million integers (O(H)time andO(H)memory forHevents).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.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 beforetimestampminus all events at or beforetimestamp - 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
_timesis strictly sorted, we can look up(hits <= x)for any integerxinO(log D)time via binary search (D= number of distinct seconds with events).Log events in O(1) time under a mutex
Because
hittimestamps 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 (
0if empty, else_prefix_counts[-1]), appendtimestampto_times, and appendprevious_total + 1to_prefix_counts.
To keep
HitCounterthread-safe, we guard_timesand_prefix_countswiththreading.Lock(). Without a mutex, two threads incrementing_prefix_counts[-1]concurrently could suffer a lost update, or a reader could observe_timesright after an append before_prefix_countsis 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)- Same second: increment
Answer window queries in O(log D) with `bisect_right`
To evaluate
_count_hits_up_to(x), we find how many entries in_timessatisfy<= xusingbisect_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] = 4Inside
getHits(timestamp), holdingself._lockensures 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_windowImplement the replay driver and trace both examples
hit_counter_operationsinstantiatesHitCounter, steps throughoperationsandargumentsin lockstep, and recordsNonefor"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)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 runbisect_righttwice over theDsorted entries in_times—once attimestampand once attimestamp - 300—and subtract the two prefix totals.hit_counter_operations:O(N log D)time acrossNcommands, since eachhitisO(1)amortized and eachgetHitsisO(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] == timestampfolds all of them into_prefix_counts[-1], so they enter and expire from the 300-second window together. - Inclusive vs. exclusive window edges (
t + 299vst + 300): Events att = 5count atgetHits(304)(304 - 300 = 4 < 5) and expire atgetHits(305)(305 - 300 = 5subtracts_prefix_counts[0]). - Queries before any hits or before all logged timestamps (Example 2): Both
bisect_rightlookups return0, producing0 - 0 = 0without counting future events. - Historical queries after newer hits (
hit(5),hit(305),getHits(120)):_count_hits_up_to(120)stops att = 5and ignorest = 305, returning1. - Wide timestamp jumps up to
2 * 10^9: Quiet periods allocate zero slots, and negative cutoffs such as20 - 300 = -280cleanly return0frombisect_right.
Common mistakes
- Off-by-one cutoff (
timestamp - 299instead oftimestamp - 300): Because[timestamp - 299, timestamp]spans 300 inclusive integer seconds, events attimestamp - 299belong inside the count; you must subtract events at or beforetimestamp - 300. - Including future hits when
getHits(t)queriestearlier than logged events: A naive queue that only pops timestamps<= t - 300and returns queue size fails Example 2 (hit(100), hit(450), getHits(80)), returning2instead of0. - Destructively discarding old entries when historical queries occur: Popping from a deque or overwriting modulo-300 slots loses counts needed if a later
getHitsqueries an earlier timestamp. - Relying on Python's GIL instead of an explicit lock: Even under CPython's Global Interpreter Lock,
self._prefix_counts[-1] += 1executes multiple bytecode instructions where threads can interleave and drop increments, or observe mismatched lengths between_timesand_prefix_counts.
Alternative approaches
- Modulo-300 ring buffer (only when
getHitsis also monotonic): Keepslot_time = [0] * 300andslot_count = [0] * 300indexed byt % 300, resettingslot_count[idx] = 1whenslot_time[idx] != tand summing buckets witht - 300 < slot_time[i] <= t. That usesO(1)memory (300integers), 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
hitandgetHits): Store[second, count]pairs incollections.dequeand pop expired front pairs<= t - 300while subtracting from a running sum, givingO(1)amortizedhitandgetHitswhen 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
hitandgetHitsinthreading.Lockguarantees atomic updates and consistent reads across_timesand_prefix_counts. Under extreme write contention across many cores, apply lock striping (partitioning intoSindependent shard counters—sayS = 16—where each writer hashes its thread ID to update one shard andgetHitssums across allSshards). 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_timesto 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_SECONDSto86,400requires zero structural changes to prefix sums, and one full day of active seconds (86,400integers) takes well under2MB. Over weeks of continuous uptime, if historical queries older than 24 hours are not needed, you can periodically compact entries older thanlatest_time - 86,400into a base offset or use an86,400-slot ring buffer maintained with a running window sum; if sub-second boundary precision is unnecessary, coarsening into1,440one-minute buckets shrinks memory by60x. - 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 (INCRBYon keyhits:<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
- How can you make the counter safe and scalable when many worker threads invoke hit and getHits concurrently?
- What happens to memory consumption if the lookback window expands to 24 hours, and what trade-offs could keep memory bounded?
- How would you redesign this counter when events land across a fleet of stateless servers rather than a single process?
Similar questions
- Microarchitecture, Cache Hierarchy, and Memory System Fundamentals
- Silicon Verification Essentials: SystemVerilog, UVM, Clock Domains, and Caches
- Accessible Expandable Tree View State and React Component
- Weekly Operating Hours Check with Overnight Windows
- Diagnosing RTL Lint Findings in Digital Design
- Playing Card Deck with Fair Shuffle and Draw
More Apple interview questions
- Technical Project Retrospective: Architecture, Design Trade-Offs, and Stakeholder Alignment Medium
- Consolidate Overlapping Intervals Medium
- Fixed-Capacity LRU Cache Operation Stream Medium Pro
- Silicon Verification Essentials: SystemVerilog, UVM, Clock Domains, and Caches Hard Pro
- Navigating Work Eligibility, Resume Accuracy, and Multi-Tier Leveling Medium Pro
- Non-Mutating Grid Island Count Medium Pro
- Target-Sum Contiguous Subarray Count Hard Pro
- Bidirectional Chain Length from an Arbitrary Node Medium Pro
- Authenticated Election APIs and Data Model Easy Pro
- Sliding 300-Second Event Counter Medium Pro