# 48ms Python Concise Solution

• ``````class HitCounter(object):

def __init__(self):
"""
"""
from collections import deque

self.num_of_hits = 0
self.time_hits = deque()

def hit(self, timestamp):
"""
Record a hit.
@param timestamp - The current timestamp (in seconds granularity).
:type timestamp: int
:rtype: void
"""
if not self.time_hits or self.time_hits[-1][0] != timestamp:
self.time_hits.append([timestamp, 1])
else:
self.time_hits[-1][1] += 1

self.num_of_hits += 1

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
"""
while self.time_hits and self.time_hits[0][0] <= timestamp - 300:
self.num_of_hits -= self.time_hits.popleft()[1]

return self.num_of_hits``````

• My solution is more concise than yours. But your solution is better for dealing with the follow-up question.

``````class HitCounter(object):

def __init__(self):
"""
"""
self.hits = collections.deque()

def hit(self, timestamp):
"""
Record a hit.
@param timestamp - The current timestamp (in seconds granularity).
:type timestamp: int
:rtype: void
"""
self.hits.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
"""
begin = max(timestamp-300, 0)
while self.hits and self.hits[0] <= begin:
self.hits.popleft()
return len(self.hits)
``````

``````class HitCounter(object):
def __init__(self):
self.arr = []
"""
"""

def hit(self, timestamp):
"""
Record a hit.
@param timestamp - The current timestamp (in seconds granularity).
:type timestamp: int
:rtype: void
"""
self.arr.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
"""
count = 0
for i in range(len(self.arr)):
if timestamp - 300 < self.arr[i] <= timestamp:
count += 1
return count
``````

``````class HitCounter:

def __init__(self):
self.hits = defaultdict(lambda: 0)

def hit(self, timestamp):
self.hits[timestamp] += 1

def getHits(self, timestamp):
return sum(self.hits[timestamp-i] for i in range(300))

``````

• @jason-junchen When you call getHits, what is the reason for subtracting from num_of_hits?

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.