Ring-Buffer Event Counter with Time Windows
Data Structure DesignAuto-graded · 13 test casesLast updated
Tests whether a candidate can implement a fixed-memory sliding-window counter using a circular array of timestamped buckets with O(1) writes and O(W) reads.
Ring-Buffer Event Counter with Time Windows
You are building a lightweight event-tracking system. The system processes a sequence of named commands, each with a single integer argument representing a second-precision timestamp. Your job is to execute those commands in order and return the result of each one.
There are two commands:
"recordHit"with argument[t]— log one event at timet. This command produces no output (None)."getHits"with argument[t]— report how many events have been recorded with timestamps strictly greater than0and at mostt. This command returns an integer.
The system keeps events in a fixed-size circular array of window_size slots. Second t is stored in slot t % window_size. Each slot holds the timestamp of the last write and a count; if two different seconds map to the same slot, the newer one overwrites the older one.
Command rules
- Timestamps across all commands (both
recordHitandgetHits) must be non-decreasing. A timestamp strictly less than the most recent timestamp seen so far raisesValueError. - An unrecognized command name raises
ValueError. - If the operation list is empty, return an empty list.
Collision handling
Because the array has only window_size slots, second t and second t + window_size share the same slot. Each slot therefore stores the exact timestamp of its most recent write alongside the count:
- If an incoming
recordHitfinds a slot whose stored timestamp equalst, it increments that slot's count (same second, same event bucket). - If the stored timestamp differs from
t, the slot holds stale data from an earlier pass around the ring. Overwrite it with timestamptand count1.
What getHits counts
When called with argument t, getHits scans every slot and sums the counts of all slots whose stored timestamp ts satisfies 0 < ts <= t. Because t is both the current time and the look-back length under this command contract, the lower bound is always 0 — events recorded at second 0 are never included.
Constraints
1 <= window_size <= 10_0000 <= len(operations) <= 10_000len(operations) == len(arguments)- Each element of
argumentsis a list containing exactly one integer. 0 <= timestamp <= 10^9- Timestamps across all operations are non-decreasing; any violation raises
ValueError. - An unknown operation name raises
ValueError. - Multiple
recordHitcalls at the same timestamp are allowed and are counted together.
Examples
Example 1
Input: ring_buffer_event_counter(['recordHit', 'recordHit', 'getHits', 'recordHit', 'getHits'], [[1], [1], [1], [2], [2]], 300)
Output: [None, None, 2, None, 3]
Hints
Hint 1
Map each timestamp to a slot with t % window_size, but store the actual timestamp alongside the count so you can tell fresh data apart from stale data that happens to share the same slot index.
Hint 2
When a recordHit arrives at slot i: if the stored timestamp matches t, increment; if it differs (or the slot is empty), reset to [t, 1]. A mismatch always means the existing data is older, because timestamps never go backward.
Hint 3
For getHits, scan all window_size slots and sum counts where 0 < stored_timestamp <= t. The lower bound is 0 because t minus t equals 0 under this contract — hits at second 0 are excluded.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Core idea: a circular array of timestamped buckets
Allocate an array of exactly window_size slots. Second t lives at index t % window_size. Because multiple seconds can share the same index (e.g. second 3 and second 303 both map to slot 3 when the window is 300), each slot stores the timestamp of its most recent write alongside the count. That tag is what lets you distinguish "this slot belongs to the current second" from "this slot is leftover from a previous lap around the ring."
recordHit
- Compute
slot = t % window_size. - Read the existing entry.
- If it is
None, or its stored timestamp differs fromt, write[t, 1]. A differing timestamp always means older data, because timestamps never decrease — safe to discard. - If the stored timestamp equals
t, increment the count. Multiple hits in the same second accumulate in one slot.
- If it is
- Append
Noneto results.
getHits
Scan every slot. Sum the count of each slot whose stored timestamp ts satisfies 0 < ts <= t. The lower bound is 0 rather than t - window_size because under this command contract the single argument is simultaneously "now" and "pastSeconds," so lower_bound = t - t = 0. Events recorded at second 0 are excluded by the strict inequality.
Why the overwrite is always safe
Timestamps are non-decreasing across all operations. When a new timestamp arrives at a slot that already holds a different timestamp, the new one is guaranteed to be larger. The evicted data is therefore older and outside any future query window — discarding it is correct.
Edge cases
| Situation | Behavior |
|---|---|
| Empty operation list | Returns [] immediately |
| Multiple hits at the same second | Accumulated in one slot; never lost |
Gap of ≥ window_size seconds | Tags differ, slot is safely overwritten |
Hit recorded at timestamp 0 | Stored but excluded by 0 < ts in getHits |
window_size == 1 | Every new second replaces the single slot |
| Decreasing timestamp | ValueError |
| Unknown operation | ValueError |
Complexity
- recordHit: O(1) — one modulo, one array read, one write.
- getHits: O(W) — scans all
window_sizeslots. Because W is fixed at construction time, this is constant with respect to the number of hits recorded. - Space: O(W) — the buffer never grows beyond
window_sizeentries regardless of traffic volume.
If O(1) getHits is required, maintain a running total and subtract a slot's old count before overwriting it. That optimization adds bookkeeping complexity and is error-prone; the O(W) scan is the clean, correct default.
Reference solution
from typing import List, Optional
def ring_buffer_event_counter(
operations: List[str],
arguments: List[List[int]],
window_size: int,
) -> List[Optional[int]]:
# Each slot is either None or [stored_timestamp, count].
buckets = [None] * window_size
results: List[Optional[int]] = []
current_time = 0
for operation, args in zip(operations, arguments):
timestamp = args[0]
if timestamp < current_time:
raise ValueError("timestamps must be non-decreasing")
current_time = timestamp
slot = timestamp % window_size
if operation == "recordHit":
bucket = buckets[slot]
if bucket is None or bucket[0] != timestamp:
# Slot is empty or holds stale data from a previous lap.
buckets[slot] = [timestamp, 1]
else:
# Same second: accumulate into the existing entry.
bucket[1] += 1
results.append(None)
elif operation == "getHits":
# Under this contract, t is both "now" and "pastSeconds",
# so lower_bound = t - t = 0. Hits at second 0 are excluded.
total = 0
for bucket in buckets:
if bucket is not None and 0 < bucket[0] <= timestamp:
total += bucket[1]
results.append(total)
else:
raise ValueError(f"unknown operation: {operation!r}")
return results