Problem

You have a RecentCounter class which counts the number of recent requests within a certain time frame.

Implement the RecentCounter class:

  • RecentCounter() Initializes the counter with zero recent requests.
  • int ping(int t) Adds a new request at time t, where t represents some time in milliseconds, and returns the number of requests that has happened in the past 3000 milliseconds (including the new request). Specifically, return the number of requests that have happened in the inclusive range [t - 3000, t].

It is guaranteed that every call to ping uses a strictly larger value of t than the previous call.

Examples

Example 1

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
**Input**
["RecentCounter", "ping", "ping", "ping", "ping"]
[[], [1], [100], [3001], [3002]]
**Output**
[null, 1, 2, 3, 3]

**Explanation**
RecentCounter recentCounter = new RecentCounter();
recentCounter.ping(1);     // requests = [_1_], range is [-2999,1], return 1
recentCounter.ping(100);   // requests = [_1_ , _100_], range is [-2900,100], return 2
recentCounter.ping(3001);  // requests = [_1_ , _100_ , _3001_], range is [1,3001], return 3
recentCounter.ping(3002);  // requests = [1, _100_ , _3001_ , _3002_], range is [2,3002], return 3

Constraints

  • 1 <= t <= 10^9
  • Each test case will call ping with strictly increasing values of t.
  • At most 104 calls will be made to ping.

Solution

Method 1 – Sliding Window with Queue

Intuition

We need to count the number of requests in the last 3000 milliseconds. Since pings arrive in increasing order, we can use a queue to store the timestamps and remove old ones from the front as new pings arrive.

Approach

  1. Use a queue to store the timestamps of pings.
  2. For each new ping at time t, add t to the queue.
  3. Remove timestamps from the front of the queue if they are less than t-3000.
  4. The size of the queue is the answer.

Code

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
#include <queue>
class RecentCounter {
    std::queue<int> q;
public:
    RecentCounter() {}
    int ping(int t) {
        q.push(t);
        while (!q.empty() && q.front() < t - 3000) q.pop();
        return q.size();
    }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
type RecentCounter struct {
    q []int
}
func Constructor() RecentCounter {
    return RecentCounter{q: []int{}}
}
func (this *RecentCounter) Ping(t int) int {
    this.q = append(this.q, t)
    for len(this.q) > 0 && this.q[0] < t-3000 {
        this.q = this.q[1:]
    }
    return len(this.q)
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
import java.util.*;
class RecentCounter {
    Queue<Integer> q = new LinkedList<>();
    public RecentCounter() {}
    public int ping(int t) {
        q.offer(t);
        while (!q.isEmpty() && q.peek() < t - 3000) q.poll();
        return q.size();
    }
}
1
2
3
4
5
6
7
8
9
import java.util.LinkedList
class RecentCounter() {
    private val q = LinkedList<Int>()
    fun ping(t: Int): Int {
        q.offer(t)
        while (q.isNotEmpty() && q.peek() < t - 3000) q.poll()
        return q.size
    }
}
1
2
3
4
5
6
7
8
9
from collections import deque
class RecentCounter:
    def __init__(self):
        self.q = deque()
    def ping(self, t: int) -> int:
        self.q.append(t)
        while self.q and self.q[0] < t - 3000:
            self.q.popleft()
        return len(self.q)
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
use std::collections::VecDeque;
struct RecentCounter {
    q: VecDeque<i32>,
}
impl RecentCounter {
    fn new() -> Self {
        Self { q: VecDeque::new() }
    }
    fn ping(&mut self, t: i32) -> i32 {
        self.q.push_back(t);
        while let Some(&front) = self.q.front() {
            if front < t - 3000 {
                self.q.pop_front();
            } else {
                break;
            }
        }
        self.q.len() as i32
    }
}
1
2
3
4
5
6
7
8
class RecentCounter {
    private q: number[] = [];
    ping(t: number): number {
        this.q.push(t);
        while (this.q.length && this.q[0] < t - 3000) this.q.shift();
        return this.q.length;
    }
}

Complexity

  • ⏰ Time complexity: O(1) amortized per ping, since each request is added and removed at most once.
  • 🧺 Space complexity: O(n), where n is the number of pings in the last 3000 ms.