Статья пока доступна только на английском.
Problem Description
Implement a RecentCounter class that counts the number of recent calls within a certain time frame.
- The
RecentCounterconstructor initializes the counter with zero recent calls. - The class has a
pingmethod that takes a parametert(the time of the call in milliseconds) and returns the number of calls that happened in the last 3000 ms.
It is guaranteed that every call to ping uses a strictly larger value of t than the previous call.
Constraints
tis in the range from 1 to 109.- Each test case calls
pingwith strictly increasing values oft. - At most 104 calls will be made to
ping.
Examples
const counter = new RecentCounter();
counter.ping(1);
counter.ping(100);
counter.ping(3001);
counter.ping(3002);
counter.ping(3003);Answer: 4
Explanation: 4 calls were made in the last 3000 ms, at times [100, 3001, 3002, 3003].
Solution
This problem is solved in literally a few lines.
To store the calls, we define a calls array inside the class, initialized as an empty array.
In the ping method we first append the time of the new call to calls and then remove from the front
all elements that fall outside the 3000 millisecond window, effectively implementing a simple queue.
Finally, we return the length of the remaining array.
export class RecentCounter {
calls: number[];
constructor() {
this.calls = [];
}
ping(t: number): number {
this.calls.push(t);
while (this.calls[0] < t - 3000) {
this.calls.shift();
}
return this.calls.length;
}
}Complexity Analysis
Time Complexity
The main cost of the ping method is the loop, which in the worst case performs 3000 iterations
to drop all stale elements, and in the best case just one.
So the complexity is O(3000) = O(1).
Space Complexity
O(1), since the maximum length of the calls array is 3000 elements.
By the problem statement, each new value is an integer strictly greater than the previous one,
so we can bound the maximum size of the array exactly.