Sliding-Window Event Counter with a Circular Bucket Buffer
Data Structure DesignAuto-graded · 23 test casesLast updated
Design a fixed-memory event counter using a ring buffer of per-second buckets that tracks how many events fell inside a trailing 15-minute window.
Sliding-Window Event Counter with a Circular Bucket Buffer
You are building a lightweight monitoring component that tracks recent activity. The component must support two operations:
record(ts)— log one event that occurred at secondts.count(now)— return the total number of events whose timestamps satisfynow - 900 < ts <= now(i.e., the most recent 15 minutes, includingnowbut excluding the second exactly 900 seconds before it).
Memory constraint
Event volume can be arbitrarily high. The implementation must use O(1) memory — specifically, a circular array of 900 integer buckets (one per second in the window). No unbounded lists, queues, or maps are allowed.
Design notes
- Timestamps are non-negative integers representing whole seconds.
- Calls arrive with non-decreasing timestamps; you will not be asked to handle out-of-order events.
countalways receives a timestamp that is ≥ every previously seen timestamp.- A bucket is considered stale when the timestamp it was last written for no longer falls inside the current 15-minute window. Stale buckets must be zeroed out before they are reused.
- A gap between consecutive calls can exceed 900 seconds; the implementation must handle this correctly.
Operations
Your function receives two parallel lists:
| parameter | meaning |
|---|---|
ops | list of strings, each "record" or "count" |
args | list of single-element lists, each containing the integer timestamp for that call |
Return a list of the same length. Each entry is None for a "record" call, or an integer for a "count" call.
Constraints
1 <= len(ops) <= 10^4len(ops) == len(args)- Every element of
argsis a list containing exactly one non-negative integer. - Timestamps are non-decreasing across all calls.
- Each timestamp satisfies
0 <= ts <= 10^9. ops[i]is either"record"or"count".
Examples
Example 1
Input: sliding_window_counter(['record', 'record', 'count', 'record', 'count', 'count'], [[1], [10], [10], [20], [20], [920]])
Output: [None, None, 2, None, 3, 0]
Example 2
Input: sliding_window_counter(['record', 'record', 'record', 'count', 'count'], [[100], [100], [100], [100], [1000]])
Output: [None, None, None, 3, 0]
Example 3
Input: sliding_window_counter(['count', 'record', 'count'], [[0], [0], [0]])
Output: [0, None, 1]
Hints
Hint 1
A circular buffer of exactly 900 slots is enough because there are only 900 distinct seconds in a 15-minute window — map each timestamp to a slot with timestamp % 900.
Hint 2
A slot can hold data from an earlier cycle. Store the actual timestamp that last wrote each slot alongside its count; if that stored timestamp doesn't match the second you're asking about, treat the slot as empty (count zero).
Hint 3
For a count query at time now, iterate over all 900 candidate seconds in the range (now-899 .. now), check each slot's stored timestamp, and sum only the non-stale counts. This is O(900) = O(1) per query.
Worked solution
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Core idea: one bucket per second in the window
The 15-minute window contains exactly 900 seconds, so a circular array of 900 slots is sufficient to cover every possible in-window second simultaneously. A timestamp ts always maps to slot ts % 900.
The key insight is stale-slot detection: two different timestamps can map to the same slot (e.g., second 0 and second 900 both map to slot 0). Storing the actual timestamp alongside the count lets us tell at a glance whether a slot holds current data or leftover data from a previous cycle. If slot_ts[slot] != ts, the slot is stale and must be cleared before being written.
record(ts)
- Compute
slot = ts % 900. - If
slot_ts[slot] != ts, this slot was last used for a different (earlier) second — zero it out and update its timestamp. - Increment
slot_ct[slot].
This is O(1) time.
count(now)
Walk every second s in the closed range [now - 899, now] (900 values). For each:
- Compute
slot = s % 900. - If
slot_ts[slot] == s, the bucket is in-window and fresh — add its count. - Otherwise the bucket is either empty or belongs to a different cycle — skip it.
Because the loop always runs exactly 900 iterations regardless of event volume, this is O(1) time (O(900) with a constant factor of 900).
Why this is correct
- Window boundary: the range
(now - 900, now]is enforced by iteratingrange(now - 899, now + 1)— that's 900 values, inclusive ofnow, exclusive ofnow - 900. - Gaps larger than 900 s: if no events were recorded for more than a full window, every slot in the range will have a mismatched timestamp and contribute 0. The answer correctly becomes 0 with no extra reset pass needed.
- Same-slot collision across cycles: the timestamp guard (
slot_ts[slot] == second) is what makes the circular reuse safe.
Complexity
| Operation | Time | Space |
|---|---|---|
record | O(1) | O(1) additional |
count | O(900) = O(1) | O(1) additional |
| Overall | O(N) for N calls | O(900) = O(1) — bounded regardless of event rate |
Reference solution
from typing import List, Optional
def sliding_window_counter(ops: List[str], args: List[List[int]]) -> List[Optional[int]]:
WINDOW = 900 # seconds in 15 minutes; also the number of buckets
# Each slot stores the timestamp it was last written for and its count.
# A slot whose stored timestamp != the second being queried is stale.
slot_ts = [None] * WINDOW
slot_ct = [0] * WINDOW
results: List[Optional[int]] = []
for op, arg in zip(ops, args):
ts = arg[0]
slot = ts % WINDOW
if op == "record":
# If the slot belongs to an earlier cycle, reset it first.
if slot_ts[slot] != ts:
slot_ts[slot] = ts
slot_ct[slot] = 0
slot_ct[slot] += 1
results.append(None)
elif op == "count":
total = 0
# Walk every second that belongs to the current window.
for second in range(ts - WINDOW + 1, ts + 1):
s = second % WINDOW
if slot_ts[s] == second: # bucket is fresh and in-window
total += slot_ct[s]
results.append(total)
else:
raise ValueError(f"Unknown operation: {op!r}")
return results