Sliding Five-Minute Hit Tally for Each Caller
Data Structure DesignAuto-graded · 27 test casesLast updated
Process a batch of hit and query operations, returning each caller's number of hits within an inclusive 300-second window, using per-caller queues with lazy expiry.
You are building a small usage tracker that counts how many requests each caller has made recently.
You are given two parallel lists, operations and args, describing a sequence of calls to be processed in order. The i-th operation is operations[i], and its parameters are in args[i], which is always a two-element list [caller_id, timestamp].
There are two kinds of operations:
"hit": record one request made bycaller_idat timetimestamp(in seconds)."getHits": report how many requestscaller_idhas made within the last 5 minutes as oftimestamp. This means every recorded hit of that caller whose time lies in the inclusive range[timestamp - 299, timestamp].
Hits from different callers are tracked completely independently of one another.
Return a list with one entry per operation, in the same order:
Nonefor every"hit".- The integer count for every
"getHits".
Rules and edge cases
- Timestamps never decrease over the whole sequence of operations. Several operations, including several hits from the same caller, may share the same timestamp, and each hit counts separately.
- A hit made exactly at
timestamp - 299is counted. A hit made attimestamp - 300or earlier is not. - A
"getHits"for a caller that has never made a hit returns0. - Hits that are too old to matter for any future query may be discarded; the design should avoid scanning all callers on each operation, and should aim for amortized constant time per operation.
Constraints
len(operations) == len(args)- Each operation is either
"hit"or"getHits". caller_idis a string;timestampis a non-negative integer.- Timestamps are non-decreasing across the entire sequence.
- Many distinct callers may appear, and most of them may be idle at any moment.
Examples
Example 1
Input: caller_hit_tally(['hit', 'hit', 'hit', 'getHits', 'getHits'], [['a', 1], ['a', 2], ['b', 3], ['a', 4], ['b', 4]])
Output: [None, None, None, 2, 1]
Example 2
Input: caller_hit_tally(['hit', 'getHits', 'hit', 'getHits'], [['a', 0], ['a', 300], ['a', 300], ['a', 300]])
Output: [None, 0, None, 1]
Example 3
Input: caller_hit_tally(['hit', 'hit', 'hit', 'getHits'], [['a', 10], ['a', 10], ['a', 10], ['a', 10]])
Output: [None, None, None, 3]
Hints
Hint 1
Keep a separate structure for each caller, keyed by caller id in a dictionary, so one caller's traffic never affects another's count.
Hint 2
Because timestamps never decrease, each caller's list of hit times is already sorted, so the oldest hits are always at the front of a queue.
Hint 3
When answering a query, remove from the front while the time is less than timestamp - 299, then the queue length is the answer. Each hit is removed at most once, giving amortized O(1). Do not create an entry when querying an unknown caller.
Worked solution
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Keep a dictionary that maps each caller id to a queue (deque) of that caller's hit timestamps.
- On
"hit", append the timestamp to the caller's queue (creating it if needed) and outputNone. - On
"getHits", look up the caller's queue. If there is none, the answer is0and nothing is created. Otherwise computecutoff = timestamp - 299, pop from the front while the front value is smaller thancutoff, and output the queue length.
Why it is correct
- Timestamps never decrease globally, so each caller's queue, which is a subsequence of the global order, is sorted. The oldest hits are therefore at the front, and popping from the front removes exactly the expired ones.
- A hit that is too old for the current query is also too old for every later query, because later timestamps are at least as large. Removing it can never change a future answer.
- The comparison is strictly
< cutoff, so a hit at exactlytimestamp - 299stays and one attimestamp - 300is removed, matching the inclusive window. - Duplicate timestamps are each stored and counted.
- Each caller has its own queue, so callers do not interfere.
Complexity
hit: O(1).getHits: amortized O(1), since each hit is appended once and popped at most once.- Space: proportional to the hits still stored, plus one entry per caller that has hit. Stale hits of a caller are only removed when that caller is queried (lazy eviction).
Reference solution
from collections import deque
from typing import List, Optional
def caller_hit_tally(operations: List[str], args: List[List]) -> List[Optional[int]]:
hits = {}
results = []
for op, arg in zip(operations, args):
caller_id, timestamp = arg
if op == 'hit':
if caller_id not in hits:
hits[caller_id] = deque()
hits[caller_id].append(timestamp)
results.append(None)
else:
q = hits.get(caller_id)
if q is None:
results.append(0)
continue
cutoff = timestamp - 299
while q and q[0] < cutoff:
q.popleft()
results.append(len(q))
return results