← 返回 databricks 的题目列表Design an API QPS Counter
类型:online_judge
Implement an in-memory API QPS counter. Record start_time when the server starts. Each request has a current timestamp in seconds (in an actual interview, system time may be used). Support the following operations:
put(key, value): records one PUT request.
get(key): records one GET request.
get_load(): returns the average GET QPS and PUT QPS separately over the last five minutes.
QPS Definition
Let now be the current timestamp and start_time be the server start timestamp:
Count requests in the trailing 300-second window: requests satisfying now - timestamp < 300.
The denominator must not always be 300. If the server has been running for fewer than 300 seconds, use its actual running time:
elapsed = min(now - start_time, 300)
qps = request_count_in_window / elapsed
If elapsed = 0, define QPS as 0.0.
A get_load() call itself does not count as either a GET or a PUT request.
key and value do not affect QPS accounting; you do not need to implement actual key-value storage semantics.
Use a fixed-size ring buffer with one bucket per second. Each operation should run in O(1) time and use O(300) space.
Input Format
For deterministic testing, timestamps are explicitly supplied. The first line contains server start time start_time; the second line contains the number of operations n; each subsequent line is one of:
timestamp PUT key value
timestamp GET key
timestamp LOAD
For every LOAD, print:
get_qps put_qps
Print both values with six decimal places.
Example
Input:
0
5
1 PUT a 1
2 GET a
3 GET b
10 LOAD
301 LOAD
Output:
0.222222 0.111111
0.000000 0.000000
At time 10, the server has run for 10 seconds and the active window contains 2 GETs and 1 PUT. At time 301, all prior requests have expired from the trailing 300-second window.
Example
Input
0
5
1 PUT a 1
2 GET a
3 GET b
10 LOAD
301 LOAD
Output
0.222222 0.111111
0.000000 0.000000