Problem

Design a hit counter which counts the number of hits received in the past 5 minutes.

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.

It is possible that several hits arrive roughly at the same time.

Examples

Example 1:

HitCounter counter = new HitCounter();

// hit at timestamp 1.
counter.hit(1);

// hit at timestamp 2.
counter.hit(2);

// hit at timestamp 3.
counter.hit(3);

// get hits at timestamp 4, should return 3.
counter.getHits(4);

// hit at timestamp 300.
counter.hit(300);

// get hits at timestamp 300, should return 4.
counter.getHits(300);

// get hits at timestamp 301, should return 3.
counter.getHits(301);

Follow up: What if the number of hits per second could be very large? Does your design scale?

Similar Problem

Design hit counter with range queries

Solution

Method 1 - Use Queue

We need to design a system that can efficiently record hits and fetch the number of hits received in the last 5 minutes (300 seconds).

Approach

  1. Data Structure: Use a queue to maintain the timestamps of hits.
  2. Record Operation: Add a new hit to the queue with the given timestamp.
  3. Get Hits Operation: Remove hits from the front of the queue that are older than 300 seconds from the current timestamp. The remaining hits in the queue are within the last 5 minutes.

Code

Java
class HitCounter {
    private Queue<Integer> hits;

    /** Initialize your data structure here. */
    public HitCounter() {
        hits = new LinkedList<>();
    }

    /** Record a hit.
        @param timestamp - The current timestamp (in seconds granularity). */
    public void hit(int timestamp) {
        hits.add(timestamp);
    }

    /** Return the number of hits in the past 5 minutes.
        @param timestamp - The current timestamp (in seconds granularity). */
    public int getHits(int timestamp) {
        while (!hits.isEmpty() && hits.peek() <= timestamp - 300) {
            hits.poll();
        }
        return hits.size();
    }
}
Python
class HitCounter:
    def __init__(self):
        self.hits: Deque[int] = deque()

    def hit(self, timestamp: int) -> None:
        self.hits.append(timestamp)

    def getHits(self, timestamp: int) -> int:
        while self.hits and self.hits[0] <= timestamp - 300:
            self.hits.popleft()
        return len(self.hits)

Complexity

  • ⏰ Time complexity: 
    • hit(timestamp)O(1) as it’s a simple enqueue operation.
    • getHits(timestamp)O(n) where n is the number of hits in the queue due to the potential need to remove outdated hits.
  • 🧺 Space complexity: O(n) where n is the number of hits within the last 300 seconds.