Rolling Ten-Minute Error Counter by Endpoint Prefix
Data Structure DesignAuto-graded · 17 test casesLast updated
Replay a log of error-recording and alert-check operations, grouping errors by URL prefix and counting those in an inclusive 600-second window against a strict threshold.
You are building a small error-rate monitor for a web service. Errors are grouped by an endpoint prefix, and an alert fires for a prefix when too many errors have occurred recently.
Implement a function that replays a sequence of operations on such a monitor and returns one result per operation.
Operations
Operations are given as two parallel lists: operations[i] is the name of the i-th operation and arguments[i] is the list of its arguments.
-
"record_error"with arguments[timestamp, url]- Logs one error for
urlat timetimestamp(an integer number of seconds). - The error is attributed to the prefix of the URL: split the URL on
/and keep the first three pieces, joined back with/. This is the host plus the first two path segments. For example,api.com/v1/users/listhas prefixapi.com/v1/users. - If the URL has fewer than three pieces after splitting, the whole split result is kept, so the prefix is the URL itself. A trailing slash yields an empty final piece, so
api.com/v1/users/has prefixapi.com/v1/users. - The result for this operation is
None.
- Logs one error for
-
"should_alert"with arguments[timestamp, prefix, threshold]- Counts the errors recorded so far whose attributed prefix is exactly equal to
prefix(the given string is used as is, not re-normalized) and whose error timessatisfiestimestamp - 600 <= s <= timestamp. Both ends of the window are inclusive. - The result is
Trueif this count is strictly greater thanthreshold, otherwiseFalse. - A prefix that has never had an error simply has a count of 0.
- Counts the errors recorded so far whose attributed prefix is exactly equal to
Any other operation name must raise a ValueError.
Details to get right
- Several errors may share the same timestamp, and each one counts separately.
- Errors may be recorded in any time order, and a check may use a timestamp earlier than some recorded errors. Only errors inside the window
[timestamp - 600, timestamp]count, so errors later thantimestampare ignored, as are errors older thantimestamp - 600. - A check never removes or alters stored errors; it only reads them.
Return value
A list with one entry per operation, in order: None for each "record_error", and a boolean for each "should_alert".
Constraints
len(operations) == len(arguments).- Timestamps are positive integers.
thresholdis a non-negative integer.- The number of operations can be large, so each operation should be fast (avoid rescanning every recorded error on each check).
Examples
Example 1
Input: replay_error_monitor(['record_error', 'record_error', 'should_alert', 'should_alert'], [[1000, 'api.com/v1/users/login'], [1200, 'api.com/v1/users/create'], [1201, 'api.com/v1/users', 1], [1201, 'api.com/v1/users', 2]])
Output: [None, None, True, False]
Hints
Hint 1
Compute the prefix once when an error is recorded, and store timestamps in a dictionary keyed by that prefix.
Hint 2
Keep each prefix's timestamps in a sorted list. Counting those in a range then needs only two binary searches rather than a full scan.
Hint 3
The window [t - 600, t] is inclusive on both sides: count = (number of values <= t) - (number of values < t - 600). Use bisect_right and bisect_left, and compare the count with the threshold using strict >.
Worked solution
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Two ideas drive the solution.
-
Group by prefix at write time. When an error is recorded, split the URL on
/, keep the first three pieces and join them back. That string is the key in a dictionary mapping each prefix to its list of error timestamps. -
Answer window queries with binary search. Keep each prefix's timestamp list sorted (using
insort). The number of errors in[t - 600, t]is the number of entries<= tminus the number of entries< t - 600:count = bisect_right(times, t) - bisect_left(times, t - 600)The result is
count > threshold, a strict comparison.
Why it is correct
- For every prefix, the stored list holds exactly one entry per recorded error with that prefix, including duplicates, and
insortkeeps it sorted. - On a sorted list,
bisect_right(times, t)counts elements<= tandbisect_left(times, lo)counts elements< lo. Their difference counts elements in the closed interval[lo, t], which matches the inclusive window. - Nothing is ever deleted, so out-of-order records and checks at earlier timestamps still give right answers. Old errors fall below
t - 600and are not counted, and errors later thantare excluded bybisect_right. - Unknown prefixes return an empty list through
dict.get, giving a count of 0 and noKeyError. - Short URLs, trailing slashes and duplicate timestamps follow directly from the split-and-join rule and from keeping duplicates in the list.
A queue that evicts old timestamps would only be safe if time never went backwards, which this problem does not promise, so the non-destructive sorted list is used.
Complexity
Let k be the number of errors stored for the relevant prefix and L the URL length.
record_error: O(L) to compute the prefix, plus O(log k) to find the position and O(k) worst case to shift list elements. It is O(1) amortized for the shift when times arrive in order.should_alert: O(log k).- Space: O(N) for N recorded errors, plus the stored prefix strings.
Reference solution
from bisect import bisect_left, bisect_right, insort
from typing import List, Optional
def replay_error_monitor(operations: List[str], arguments: List[List]) -> List[Optional[bool]]:
errors = {}
results = []
def prefix_of(url):
parts = url.split('/')
return '/'.join(parts[:3])
for operation, args in zip(operations, arguments):
if operation == "record_error":
timestamp, url = args
prefix = prefix_of(url)
insort(errors.setdefault(prefix, []), timestamp)
results.append(None)
elif operation == "should_alert":
timestamp, prefix, threshold = args
times = errors.get(prefix, [])
count = bisect_right(times, timestamp) - bisect_left(times, timestamp - 600)
results.append(count > threshold)
else:
raise ValueError("unknown operation")
return results