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 * 109timestamp is monotonically increasing).300 calls will be made to hit and getHits.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:
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:
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_hitsTo 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:
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| Case | How to Handle |
|---|---|
| Multiple hits arriving at the exact same timestamp | The system must properly increment the count or store multiple occurrences to reflect the true volume of traffic. |
| Timestamps arriving out of chronological order | 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 | The getHits method must return zero immediately without throwing null pointer or index out of bounds exceptions. |
| Hits occurring outside the 300-second window | 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 | 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 | 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 | The counter must completely reset or clear all expired entries when a new hit arrives long after the previous one. |