Taro Logo

Design Hit Counter

Medium
Asked by:
Google
Amazon
Uber
Apple
3.5K views
Topics:
Arrays

Design a hit counter which counts the number of hits received in the past 5 minutes (i.e., the past 300 seconds). Each hit is recorded with a timestamp that is an integer representing seconds elapsed since the beginning of time.

You should implement the following methods:

  • HitCounter() Initializes the object of the hit counter system.
  • void hit(int timestamp) Records a hit that happened at timestamp (in seconds). Several hits may occur at the same same timestamp.
  • int getHits(int timestamp) Returns the number of hits in the past 5 minutes from timestamp (i.e., the past 300 seconds).

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 * 109
  • All the calls are being made to the methods in chronological order (i.e., timestamp is monotonically increasing).
  • At most 300 calls will be made to hit and getHits.

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. Can multiple hits arrive at the exact same timestamp, and if so, should they be recorded and counted as separate hits?
  2. Are the incoming timestamps guaranteed to be strictly chronological, or could we receive hits out of order (e.g., a hit at t=100 arriving after a hit at t=150)?
  3. What is the maximum scale of incoming hits we should expect per second or overall, and is memory usage a strict constraint we need to optimize for?
  4. When we query for hits in the past 5 minutes (300 seconds) from a given timestamp $t$, is the time window inclusive or exclusive of $t-300$?
  5. What data type should be used for the timestamps (e.g., 32-bit integer, 64-bit long), and what is the maximum possible value a timestamp can reach?

Brute Force Solution

Approach

To keep track of website hits using the brute force method, you can simply write down every single hit that happens on a special list along with the exact time it occurred. Whenever someone asks how many hits happened in the last five minutes, you look at every single entry on your list from start to finish and count the ones that fall within that recent time window.

Here's how the algorithm would work step-by-step:

  1. Whenever a new hit comes in, add it to the end of your master list of all hits.
  2. When someone asks for the hit count for the recent time window, look at the current time to figure out the oldest time you care about.
  3. Go through your entire list of hits, examining every single one from the very beginning to the very end.
  4. For each hit you examine, check if its timestamp is recent enough to fall within the allowed window.
  5. Keep a running tally of every hit that passes this check.
  6. Once you have looked at every single hit on your list, give the final tally as the answer.

Code Implementation

class HitCounter:
    def __init__(self):
        self.all_recorded_hits = []

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

    def get_hits(self, timestamp: int) -> int:
        # We need the threshold to determine which historical hits fall outside the five minute window
        window_start_time = timestamp - 300
        
        total_recent_hits = 0

        # Scanning the entire master list is necessary because brute force checks every single recorded hit
        for recorded_timestamp in self.all_recorded_hits:
            if recorded_timestamp > window_start_time:
                total_recent_hits += 1

        return total_recent_hits

Big(O) Analysis

Time Complexity
O(n) – When a hit occurs, appending it to the list takes constant time, but querying the hit count requires a full traversal of all recorded hits. Specifically, for n total hits currently stored in the master list, the getHits method iterates through every single entry from the beginning to the end to check its timestamp. This means the total operations scale directly with the number of stored hits n, leading to a linear time complexity of O(n).
Space Complexity
O(N) – The auxiliary space is driven by the master list of all hits, where N represents the total number of hit events recorded over time. Each incoming hit is appended to this underlying dynamic array as a new entry alongside its timestamp. Consequently, the extra memory required grows directly in proportion to the total number of recorded hits.

Optimal Solution

Approach

To keep track of hits efficiently without saving every single click forever, we can use a system that groups hits by specific time slots. By focusing only on the active window of time that matters, we can quickly count recent activity without wasting memory.

Here's how the algorithm would work step-by-step:

  1. Imagine a timeline broken down into fixed intervals, like individual seconds over a span of five minutes.
  2. Pair each time slot with a counter that starts at zero, so you have a dedicated spot for every moment within your window.
  3. When a new hit happens, look at the current time and update the matching time slot by adding one to its counter.
  4. If a hit comes in for a time slot that was already used in an earlier cycle, reset that slot first before recording the new hit.
  5. When someone asks for the total number of recent hits, look across all the time slots within the valid window.
  6. Add up the numbers stored in those specific slots, making sure to ignore any outdated slots from earlier times.
  7. Return this total sum as the final count of hits that occurred within the allowed timeframe.

Code Implementation

class HitCounter:

    def __init__(self):
        self.time_window_size = 300
        self.timestamp_slots = [0] * self.time_window_size
        self.counter_slots = [0] * self.time_window_size

    def hit(self, timestamp: int) -> None:
        slot_index = timestamp % self.time_window_size
        
        # Reset outdated slots to prevent counting old hits from previous cycles.
        if self.timestamp_slots[slot_index] != timestamp:
            self.timestamp_slots[slot_index] = timestamp
            self.counter_slots[slot_index] = 0
            
        self.counter_slots[slot_index] += 1

    def get_hits(self, timestamp: int) -> int:
        total_hit_count = 0
        
        # Iterate through all slots to aggregate hits within the valid time window.
        for slot_index in range(self.time_window_size):
            if timestamp - self.timestamp_slots[slot_index] < self.time_window_size:
                total_hit_count += self.counter_slots[slot_index]
                
        return total_hit_count

Big(O) Analysis

Time Complexity
O(1) – When a hit occurs, we directly access and update the specific time slot in constant time using modulo arithmetic. When counting recent hits, we iterate through a fixed-size array of 300 slots representing the five-minute window. Since the number of operations for both hit and getHits is bound by this constant window size rather than the total number of incoming hits, the time complexity remains constant.
Space Complexity
O(1) – The auxiliary space is determined by fixed-size data structures representing the timeline of 300 seconds, maintaining an array of timestamps and an array of hits of constant length 300. Because the storage required does not grow with the number of incoming hits or time passing, the extra memory remains strictly bounded. Therefore, the overall auxiliary space complexity simplifies to O(1) constant space.

Edge Cases

Multiple hits arriving at the exact same timestamp
How to Handle:
The system must properly increment the count or store multiple occurrences to reflect the true volume of traffic.
Timestamps arriving out of chronological order
How to Handle:
Using a data structure like a min-heap or bucket array requires handling non-monotonic time inputs gracefully without breaking the sliding window.
Queries for hits when the data structure is completely empty
How to Handle:
The getHits method must return zero immediately without throwing null pointer or index out of bounds exceptions.
Hits occurring outside the 300-second window
How to Handle:
Stale hits older than timestamp minus 300 must be filtered out or evicted to maintain an accurate count of recent traffic.
Extremely high concurrency and high frequency of hits over long periods
How to Handle:
The solution should use a memory-efficient approach like bucket aggregation rather than storing every individual hit infinitely to prevent memory exhaustion.
Timestamp values reaching maximum integer limits
How to Handle:
The underlying data types must be large enough to prevent integer overflow when dealing with massive Unix epoch timestamps in seconds.
A large time gap between consecutive hit calls exceeding 300 seconds
How to Handle:
The counter must completely reset or clear all expired entries when a new hit arrives long after the previous one.