Skip to content

Commit bf63913

Browse files
Create design_hit_counter.py
LC 362
1 parent 8f93961 commit bf63913

1 file changed

Lines changed: 39 additions & 0 deletions

File tree

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
from collections import deque
2+
3+
4+
class HitCounter:
5+
"""
6+
A counter that records hits (events) and can return
7+
the number of hits in the past 5 minutes (300 seconds).
8+
9+
>>> hc = HitCounter()
10+
>>> hc.hit(1)
11+
>>> hc.hit(2)
12+
>>> hc.hit(300)
13+
>>> hc.get_hits(300)
14+
3
15+
>>> hc.get_hits(301)
16+
2
17+
"""
18+
19+
def __init__(self) -> None:
20+
self.hits: deque[int] = deque()
21+
22+
def hit(self, timestamp: int) -> None:
23+
"""Record a hit at the given timestamp (in seconds)."""
24+
self.hits.append(timestamp)
25+
26+
def get_hits(self, timestamp: int) -> int:
27+
"""
28+
Return the number of hits in the past 5 minutes
29+
from the given timestamp.
30+
"""
31+
while self.hits and self.hits[0] <= timestamp - 300:
32+
self.hits.popleft()
33+
return len(self.hits)
34+
35+
36+
if __name__ == "__main__":
37+
import doctest
38+
39+
doctest.testmod()

0 commit comments

Comments
 (0)