-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path362 Design Hit Counter.py
50 lines (39 loc) · 1.26 KB
/
362 Design Hit Counter.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
"""
Premium Question
Author: Rajeev Ranjan
"""
from collections import deque
class HitCounter(object):
def __init__(self):
"""
Initialize your data structure here.
calls are being made to the system in chronological order.
It is possible that several hits arrive roughly at the same time.
What if the number of hits per second could be very large? Does your design scale? # use counter
"""
self.q = deque()
def hit(self, timestamp):
"""
Record a hit.
@param timestamp - The current timestamp (in seconds granularity).
:type timestamp: int
:rtype: void
"""
self.pop(timestamp)
self.q.append(timestamp)
def getHits(self, timestamp):
"""
Return the number of hits in the past 5 minutes.
@param timestamp - The current timestamp (in seconds granularity).
:type timestamp: int
:rtype: int
"""
self.pop(timestamp)
return len(self.q)
def pop(self, timestamp):
while self.q and timestamp - self.q[0] >= 300:
self.q.popleft()
# Your HitCounter object will be instantiated and called as such:
# obj = HitCounter()
# obj.hit(timestamp)
# param_2 = obj.getHits(timestamp)