← Back to companies
[ OK ] Loaded —
[ INFO ]
$ cd
$ ls -lt
01
02
03
04
05
$ ls -lt
01
02
03
04
05
user@intervues:~/$
Design an in-memory hit counter that can calculate the average load (QPS - queries per second) over a specified time window. The system should efficiently handle variable time windows, from seconds to minutes.
HitCounter hitCounter = new HitCounter(300);`java import java.util.LinkedList; import java.util.Queue;
class HitCounter { private Queue<Integer> hits; private int windowSize;
public HitCounter(int windowSize) {
this.hits = new LinkedList<>();
this.windowSize = windowSize;
}
public void hit(int timestamp) {
// Remove outdated hits
while (!hits.isEmpty() && hits.peek() < timestamp - windowSize) {
hits.poll();
}
// Add the current hit
hits.offer(timestamp);
}
public int get(int timestamp) {
// Remove outdated hits
while (!hits.isEmpty() && hits.peek() < timestamp - windowSize) {
hits.poll();
}
// Calculate the number of hits within the window
return hits.size();
}
} `
This solution uses a queue to store timestamps of hits. When a new hit is added, it removes any hits that are outside the current window. When calculating the number of hits within the window, it also removes outdated hits. This ensures that the queue always contains hits within the current window, allowing for efficient calculation of the average load.