Problem
You are building a lightweight in-memory component that tracks the query load (QPS) of a service.
Design a data structure with two operations:
-
record(timestamp)
— called once per incoming request.
-
getQPS(timestamp)
— returns the
average QPS over the last 5 minutes
ending at
timestamp
.
Define the QPS at time t as:
QPS(t)=300#{requests with time∈(t−300, t]}
Requirements / Constraints
-
Timestamps are in
seconds
.
-
Calls to
record
and
getQPS
may be interleaved.
-
Assume timestamps are
non-decreasing
across calls.
-
Aim for efficient per-call time complexity.
Follow-ups
-
How would you implement this using a
sliding window
?
-
How can you
reduce memory usage
while keeping performance good (e.g., avoid storing every request timestamp)?