Sliding Window Hit Counter
Data Structure DesignAuto-graded · 21 test casesLast updated
Tests ability to design time-windowed event counters with efficient memory management and query performance using sliding-window techniques.
Design an in-memory hit counter that tracks events within a rolling 5-minute time window.
Your task is to implement a function that processes a sequence of operations on a hit counter. The counter supports two operations:
hit(timestamp) – Records an event at the given timestamp (measured in seconds).
getHits(timestamp) – Returns the count of all events that occurred within the 5-minute window ending at timestamp. Specifically, it counts events in the closed interval [timestamp - 299, timestamp].
You are given two parallel lists:
operations: a list of operation names, each either"hit"or"getHits"arguments: a list where each element is a single-item list[timestamp]
Return a list of results where:
- Each
"hit"operation producesNone - Each
"getHits"operation produces an integer (the count) - Any unrecognized operation raises a
ValueError
Assumptions:
- Timestamps are non-decreasing across all operations (they never go backwards, but consecutive operations may share the same timestamp)
- You should optimize memory by discarding data that falls outside the 5-minute window
- Aim for better than O(n) time complexity per query, where n is the total number of hits processed
Constraints
1 <= len(operations) <= 10^5operations[i]is"hit"or"getHits"0 <= timestamp <= 10^9- Timestamps are non-decreasing
len(operations) == len(arguments)- Each
arguments[i]contains exactly one integer
Examples
Example 1
Input: sliding_window_hit_counter(['hit', 'hit', 'hit', 'getHits', 'getHits', 'getHits'], [[1], [2], [3], [4], [300], [301]])
Output: [None, None, None, 3, 3, 2]
Example 2
Input: sliding_window_hit_counter(['hit', 'hit', 'hit', 'hit', 'getHits', 'getHits'], [[100], [100], [100], [399], [399], [400]])
Output: [None, None, None, None, 4, 1]
Example 3
Input: sliding_window_hit_counter(['getHits', 'hit', 'hit', 'getHits'], [[10], [10], [10], [10]])
Output: [0, None, None, 2]
Hints
Hint 1
Think about what happens to old events as time moves forward—do you need to keep them forever?
Hint 2
Group events that happen in the same second together to save space and avoid storing millions of individual timestamps.
Hint 3
Maintain a running total that you update incrementally rather than recalculating the sum on every query.
Worked solution
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The core insight is that this is a sliding window problem where events enter on the right and expire on the left as time advances. A queue naturally models this behavior.
Two optimizations make the solution efficient:
-
Compress events by timestamp. Instead of storing every individual hit, group all hits that occur in the same second into a single bucket
[timestamp, count]. Since timestamps never decrease, repeated timestamps can only match the last bucket in the queue, making the merge operation constant time. -
Maintain a running total. Keep a counter that increments when hits are added and decrements when buckets expire. This allows queries to return the count in O(1) without scanning or summing.
Before processing each operation (including hits), we evict all buckets whose timestamp falls outside the current 5-minute window. The window for time t is [t - 299, t], so we remove buckets where timestamp < t - 299.
Why this works:
- The queue stays sorted by timestamp because we only append to the back and timestamps are non-decreasing
- Expired buckets are removed from the front, preserving order
- The running total always reflects the sum of counts in the current window
- Once a bucket expires, it can never become relevant again (time doesn't go backwards)
Time Complexity: Amortized O(1) per operation. Each bucket is enqueued once and dequeued at most once. A single operation might evict up to 300 buckets (one per second in the window), but this cost is O(1) with respect to the number of hits.
Space Complexity: O(min(300, distinct_timestamps)) = O(1). Memory is bounded by the number of distinct seconds in a 5-minute window, not by the volume of hits.
from collections import deque
from typing import List, Optional
def sliding_window_hit_counter(operations, arguments):
buckets = deque() # each entry is [timestamp, count]
running_total = 0
output = []
def evict_expired(current_time):
nonlocal running_total
threshold = current_time - 299
while buckets and buckets[0][0] < threshold:
_, cnt = buckets.popleft()
running_total -= cnt
for op, args in zip(operations, arguments):
ts = args[0]
evict_expired(ts)
if op == "hit":
if buckets and buckets[-1][0] == ts:
buckets[-1][1] += 1
else:
buckets.append([ts, 1])
running_total += 1
output.append(None)
elif op == "getHits":
output.append(running_total)
else:
raise ValueError("unknown operation")
return output