933. Number of Recent Calls
Explanation:
- We can use a queue to keep track of the requests within the time frame of 3000 milliseconds.
- When a new request comes in, we remove all requests outside the time frame from the front of the queue.
- We add the new request to the back of the queue and return the size of the queue, which represents the number of requests within the time frame. Solution:
class RecentCounter {
Queue<Integer> requests;
public RecentCounter() {
requests = new LinkedList<>();
}
public int ping(int t) {
while (!requests.isEmpty() && requests.peek() < t - 3000) {
requests.poll();
}
requests.offer(t);
return requests.size();
}
}
Code Editor (Testing phase)
Improve Your Solution
Use the editor below to refine the provided solution. Select a programming language and try the following:
- Add import statement if required.
- Optimize the code for better time or space complexity.
- Add test cases to validate edge cases and common scenarios.
- Handle error conditions or invalid inputs gracefully.
- Experiment with alternative approaches to deepen your understanding.
Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.