Design Hit Counter Problem
Description
LeetCode Problem 362.
Design a hit counter which counts the number of hits received in the past 5 minutes (i.e., the past 300 seconds).
Your system should accept a timestamp parameter (in seconds granularity), and you may assume that calls are being made to the system in chronological order (i.e., timestamp is monotonically increasing). Several hits may arrive roughly at the same time.
Implement the HitCounter class:
HitCounter()Initializes the object of the hit counter system.void hit(int timestamp)Records a hit that happened attimestamp(in seconds). Several hits may happen at the sametimestamp.int getHits(int timestamp)Returns the number of hits in the past 5 minutes fromtimestamp(i.e., the past300seconds).
Example 1:
Input
["HitCounter", "hit", "hit", "hit", "getHits", "hit", "getHits", "getHits"]
[[], [1], [2], [3], [4], [300], [300], [301]]
Output
[null, null, null, null, 3, null, 4, 3]
Explanation
HitCounter hitCounter = new HitCounter();
hitCounter.hit(1); // hit at timestamp 1.
hitCounter.hit(2); // hit at timestamp 2.
hitCounter.hit(3); // hit at timestamp 3.
hitCounter.getHits(4); // get hits at timestamp 4, return 3.
hitCounter.hit(300); // hit at timestamp 300.
hitCounter.getHits(300); // get hits at timestamp 300, return 4.
hitCounter.getHits(301); // get hits at timestamp 301, return 3.
Constraints:
1 <= timestamp <= 2 * 10^9- All the calls are being made to the system in chronological order (i.e.,
timestampis monotonically increasing). - At most
300calls will be made tohitandgetHits.
Follow up: What if the number of hits per second could be huge? Does your design scale?
Solution
Approach: Queue of Recent Hits
Timestamps arrive in increasing order, so a hit that is too old for one getHits call is too old for every later call too. That suggests a queue: keep the timestamps of the hits in arrival order, and drop old ones from the front as time moves on.
hit(timestamp): addtimestampto the back of the queue.getHits(timestamp): the window is the past 300 seconds,timestamp - 299totimestamp. A hit attis outside it oncet <= timestamp - 300. Remove such hits from the front, then return the size of the queue.
Check the boundary with the example: after hits at 1, 2, 3 and 300, getHits(300) returns 4. getHits(301) drops the hit at 1 (since 1 <= 301 - 300) and returns 3.
Each hit is added once and removed at most once, so the work is spread evenly over the calls.
Follow-up: with a huge number of hits per second, storing each hit uses too much memory. Keep 300 buckets instead, one per second of the window. Each bucket stores a timestamp and a count, and bucket t % 300 collects the hits of second t. It is reset when it still holds an older second. getHits adds up the buckets whose timestamp is within the last 300 seconds. That gives O(1) per hit, O(300) per query and constant memory.
Complexity: O(1) amortized time per call. O(h) space for the h hits in the current window.
from collections import deque
class HitCounter:
def __init__(self):
self.hits = deque() # timestamps of the hits in the last 300 seconds, oldest first
def hit(self, timestamp: int) -> None:
self.hits.append(timestamp)
def getHits(self, timestamp: int) -> int:
# a hit at time t is too old once t <= timestamp - 300
while self.hits and self.hits[0] <= timestamp - 300:
self.hits.popleft()
return len(self.hits)