444. Recent Pings

A monitoring dashboard receives heartbeat signals from a server and shows how busy the server has been lately. Each signal comes with its arrival time in milliseconds, and the dashboard needs the number of signals that arrived in the most recent three seconds, counting the current one.

Implement the class RecentPings with a constructor that takes no arguments and a method ping(t). A call records a signal that arrived at time t and returns how many recorded signals, including this one, have an arrival time in the inclusive range [t - 3000, t]. The times passed to ping are strictly increasing across calls, so older signals never come back into the window.

Example 1

Input:
operations = ["RecentPings","ping","ping","ping","ping","ping"]arguments = [[],[410],[2010],[3410],[3411],[6600]]
Output:
[null,1,2,3,3,1]
Explanation:

At 3410 the window is [410, 3410] and holds all three signals so far. At 3411 the window starts at 411, so 410 drops out: 2010, 3410, 3411 remain, giving 3. At 6600 the window is [3600, 6600], which holds only the new signal.

Example 2

Input:
operations = ["RecentPings","ping","ping","ping","ping"]arguments = [[],[7],[2999],[3007],[3008]]
Output:
[null,1,2,3,3]
Explanation:

The window at 3007 is [7, 3007] and still contains time 7 (boundary included), so the answer is 3; at 3008 time 7 has just left the window, leaving 2999, 3007 and 3008.

Constraints

1 ≤ t ≤ 109
Every call to ping uses a strictly larger t than the previous call
At most 104 calls in total.

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Input
Each case is an operation log. operations names the class first and then each method call; arguments holds the arguments for each, in the same order. Your answer is one list with a result per operation - null for the constructor and for methods that return nothing.

Expected complexity

Time
O(1) amortized per call
Space
O(w)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…

operations names the class, then each method to call; arguments holds one list of arguments per operation, in the same order.