Google
362 Design Hit Counter

1. Question

Design a hit counter which counts the number of hits received in the past 5 minutes.
Each function accepts a timestamp parameter (in seconds granularity) and you may assume that calls are being made to the system in chronological order (ie, the timestamp is monotonically increasing). You may assume that the earliest timestamp starts at 1.
It is possible that several hits arrive roughly at the same time.
Example:
1
HitCounter counter = new HitCounter();
2
3
// hit at timestamp 1.
4
counter.hit(1);
5
6
// hit at timestamp 2.
7
counter.hit(2);
8
9
// hit at timestamp 3.
10
counter.hit(3);
11
12
// get hits at timestamp 4, should return 3.
13
counter.getHits(4);
14
15
// hit at timestamp 300.
16
counter.hit(300);
17
18
// get hits at timestamp 300, should return 4.
19
counter.getHits(300);
20
21
// get hits at timestamp 301, should return 3.
22
counter.getHits(301);
Copied!
Follow up: What if the number of hits per second could be very large? Does your design scale?

2. Implementation

1
class HitCounter {
2
Queue<Integer> queue;
3
4
/** Initialize your data structure here. */
5
public HitCounter() {
6
queue = new LinkedList<>();
7
}
8
9
/** Record a hit.
10
@param timestamp - The current timestamp (in seconds granularity). */
11
public void hit(int timestamp) {
12
queue.add(timeStamp);
13
}
14
15
/** Return the number of hits in the past 5 minutes.
16
@param timestamp - The current timestamp (in seconds granularity). */
17
public int getHits(int timestamp) {
18
while (!queue.isEmpty() && (timeStamp - queue.peek() >= 300)) {
19
queue.remove();
20
}
21
return queue.size();
22
}
23
}
24
25
/**
26
* Your HitCounter object will be instantiated and called as such:
27
* HitCounter obj = new HitCounter();
28
* obj.hit(timestamp);
29
* int param_2 = obj.getHits(timestamp);
30
*/
Copied!

3. Time & Space Complexity

时间复杂度: hit(): O(1), getHits(): O(1)
空间复杂度: O(n),n是第一次call hit()的次数