Count Lower Readings in a Trailing Time Window
Data Structure DesignAuto-graded · 21 test casesLast updated
Simulate a sequence of record and query operations over a timestamped stream, counting readings in a trailing window that are strictly lower than the latest reading.
Spike Counter over a Metric Stream
You are given a log of operations performed on a metric monitor. The monitor receives numeric readings tagged with integer timestamps (in seconds) and can be asked how many recent readings are lower than the newest one.
Implement a function that replays the operations in order and returns one output per operation.
Operations
You receive two parallel lists, operations and arguments. The i-th entry of arguments holds the arguments for the i-th entry of operations.
"record"with arguments[timestamp, value]: store a reading with the given integer timestamp and integer value. The output for this operation isNone."get_spike_count"with arguments[window_size]: the output is the number of stored readings that satisfy both of the following:- The reading lies inside the trailing window of
window_sizeseconds. - Its value is strictly less than the value of the most recently recorded reading.
- The reading lies inside the trailing window of
Precise Rules
- The "current" reading is the reading recorded most recently (the last
recordperformed so far), not a separate query time. - Let
tbe the timestamp of the current reading. The trailing window is the inclusive range of integer seconds[t - window_size + 1, t]. A reading is inside the window if its timestamp is in this range. - The current reading is never counted, since its value is not strictly less than itself. Other readings with the same timestamp as the current one are counted if they are inside the window and have a smaller value.
- Readings with a value equal to the current value are not counted.
- If nothing has been recorded yet, the answer to a query is
0. - If
window_sizeis zero or negative, the window contains no readings and the answer is0. - A window that reaches back before the earliest reading simply includes all readings up to that point.
- Queries do not modify any stored data. Later queries use whatever has been recorded up to that moment.
Output
Return a list with the same length as operations. Entries for "record" are None; entries for "get_spike_count" are integers.
Constraints
len(operations) == len(arguments).- Timestamps in
recordoperations are integers and arrive in non-decreasing order. - Values and
window_sizeare integers. - Every operation name is either
"record"or"get_spike_count".
Examples
Example 1
Input: count_lower_readings(['record', 'record', 'record', 'record', 'record', 'get_spike_count'], [[1, 10], [2, 5], [3, 12], [4, 8], [5, 15], [3]])
Output: [None, None, None, None, None, 2]
Hints
Hint 1
Because timestamps never decrease, the readings inside any trailing window always form a contiguous block at the end of the history.
Hint 2
Work out the earliest timestamp that is still inside the window as `current_timestamp - window_size + 1`, then count only readings from that point on whose value is below the latest value.
Hint 3
To skip older readings quickly, keep timestamps in a list and use binary search (`bisect_left`) to find where the window begins. Do not discard old readings, because later queries may use a larger window.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Keep two parallel lists: the timestamps and the values of every recorded reading, in arrival order. A record operation just appends to both lists and outputs None.
For a get_spike_count query:
- If nothing has been recorded, the answer is
0. - Take the latest reading
(t, v). - Compute
cutoff = t - window_size + 1. A reading is inside the window exactly when its timestamp is at leastcutoff(no reading has a timestamp abovet). - Because timestamps are non-decreasing, the list is sorted.
bisect_left(timestamps, cutoff)gives the first index inside the window, and everything from there to the end is inside the window. - Count the values in that suffix that are strictly less than
v.
Why It Is Correct
- The window condition is
cutoff <= timestamp <= t. The upper bound always holds, sincetis the largest timestamp so far. - Sortedness means the readings that satisfy the lower bound form a suffix of the list, and binary search finds its start precisely.
- Counting only values strictly below
vautomatically excludes the current reading and any reading equal in value to it, while still counting smaller readings sharing the current timestamp. - If
window_size <= 0, thencutoff > t, so the suffix is empty and the count is0. - If the window reaches before the first reading,
bisect_leftreturns0and all readings are examined. - Old readings are never discarded, because window sizes vary between queries, and a later query may need readings that an earlier small window would have dropped.
Complexity
Let n be the number of readings recorded so far and w the number of readings in the queried window.
record: O(1) amortized.get_spike_count: O(log n) for the binary search plus O(w) for counting, so O(w), and O(n) in the worst case.- Space: O(n).
For sublinear queries, the counting step is a range-rank query (how many values in an index range are below a threshold), which can be handled by a merge-sort tree, a wavelet tree, or an offline Fenwick-tree sweep.
Reference Solution
from bisect import bisect_left
from typing import List, Optional
def count_lower_readings(operations: List[str], arguments: List[List[int]]) -> List[Optional[int]]:
timestamps: List[int] = []
values: List[int] = []
results: List[Optional[int]] = []
for operation, args in zip(operations, arguments):
if operation == "record":
timestamp, value = args
timestamps.append(timestamp)
values.append(value)
results.append(None)
elif operation == "get_spike_count":
window_size = args[0]
if not values:
results.append(0)
continue
current_timestamp = timestamps[-1]
current_value = values[-1]
cutoff = current_timestamp - window_size + 1
start = bisect_left(timestamps, cutoff)
count = 0
for i in range(start, len(values)):
if values[i] < current_value:
count += 1
results.append(count)
else:
raise ValueError("Unknown operation: " + operation)
return results