Algo-Sim › Low-Level Design

Design Hit Counter

Medium · Low-Level Design · step through it in Java, Python and C++ on your own input

Count hits in the last 5 minutes: a queue of timestamps, dropping expired ones from the front. Each hit is pushed and popped once, so O(1) amortized.

Problem

Design a hit counter. hit(timestamp) records a hit at that second, and getHits(timestamp) returns how many hits happened in the past 300 seconds, that is in (timestamp − 300, timestamp]. Calls arrive in non-decreasing time order.

Constraints

Edge cases to test

Follow-up questions

What if hits arrive at huge rates?
Use 300 buckets of (timestamp, count) indexed by t % 300: O(1) memory and O(300) per query.
How do you scale it across machines?
Count locally per bucket and merge the buckets from every server when reading.

Solution

Java

class HitCounter {
    private final Deque<Integer> hits = new ArrayDeque<>();   // timestamps, oldest first

    public void hit(int timestamp) {
        hits.addLast(timestamp);
    }

    public int getHits(int timestamp) {
        while (!hits.isEmpty() && hits.peekFirst() <= timestamp - 300)
            hits.pollFirst();
        return hits.size();
    }
}

Python

from collections import deque


class HitCounter:
    def __init__(self):
        self.hits = deque()                 # timestamps, oldest first

    def hit(self, timestamp):
        self.hits.append(timestamp)

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

C++

#include <bits/stdc++.h>
using namespace std;

class HitCounter {
  public:
    deque<int> hits = {}; // timestamps, oldest first

    void hit(int timestamp) {
        hits.push_back(timestamp);
    }

    int getHits(int timestamp) {
        while (!hits.empty() && hits.front() <= timestamp - 300)
            hits.pop_front();
        return int(hits.size());
    }
};

More Low-Level Design problems