Skip to content

Commit 0b43a10

Browse files
authored
Create Design Hit Counter.py
1 parent df63da7 commit 0b43a10

File tree

1 file changed

+72
-0
lines changed

1 file changed

+72
-0
lines changed

Design Hit Counter.py

Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
'''
2+
Design a hit counter which counts the number of hits received in the past 5 minutes.
3+
4+
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.
5+
6+
It is possible that several hits arrive roughly at the same time.
7+
8+
Example:
9+
HitCounter counter = new HitCounter();
10+
11+
// hit at timestamp 1.
12+
counter.hit(1);
13+
14+
// hit at timestamp 2.
15+
counter.hit(2);
16+
17+
// hit at timestamp 3.
18+
counter.hit(3);
19+
20+
// get hits at timestamp 4, should return 3.
21+
counter.getHits(4);
22+
23+
// hit at timestamp 300.
24+
counter.hit(300);
25+
26+
// get hits at timestamp 300, should return 4.
27+
counter.getHits(300);
28+
29+
// get hits at timestamp 301, should return 3.
30+
counter.getHits(301);
31+
Follow up:
32+
What if the number of hits per second could be very large? Does your design scale?
33+
34+
Credits:
35+
Special thanks to @elmirap for adding this problem and creating all test cases.
36+
'''
37+
38+
class HitCounter(object):
39+
40+
def __init__(self):
41+
"""
42+
Initialize your data structure here.
43+
"""
44+
self.vec = collections.deque()
45+
46+
47+
def hit(self, timestamp):
48+
"""
49+
Record a hit.
50+
@param timestamp - The current timestamp (in seconds granularity).
51+
:type timestamp: int
52+
:rtype: void
53+
"""
54+
self.vec.append(timestamp)
55+
56+
def getHits(self, timestamp):
57+
"""
58+
Return the number of hits in the past 5 minutes.
59+
@param timestamp - The current timestamp (in seconds granularity).
60+
:type timestamp: int
61+
:rtype: int
62+
"""
63+
while len(self.vec) > 0 and timestamp - self.vec[0] >= 300:
64+
self.vec.popleft()
65+
66+
return len(self.vec)
67+
68+
69+
# Your HitCounter object will be instantiated and called as such:
70+
# obj = HitCounter()
71+
# obj.hit(timestamp)
72+
# param_2 = obj.getHits(timestamp)

0 commit comments

Comments
 (0)