LeetCode 362: Design Hit Counter Solution
Master LeetCode problem 362 (Design Hit Counter), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
362. Design Hit Counter
Problem Explanation
Explanation:
To design a hit counter, we can consider using two data structures:
- An array to store the timestamp of each hit.
- A queue to store the count of hits within the last 300 seconds (5 minutes).
Algorithm:
- Initialize two arrays,
timestampsto store timestamps andhitsto store the count of hits. - For each hit, increment the count in the
hitsarray at the corresponding timestamp index. - When a hit occurs, remove all timestamps older than 300 seconds from the
timestampsarray and adjust the hit count in thehitsarray accordingly. - To get the total number of hits in the last 300 seconds, sum up all the counts in the
hitsarray.
Time Complexity: O(1) for hit and O(n) for getting hits in the last 300 seconds. Space Complexity: O(n), where n is the number of hits within the last 300 seconds.
:
Solution Code
class HitCounter {
private int[] timestamps;
private int[] hits;
public HitCounter() {
timestamps = new int[300];
hits = new int[300];
}
public void hit(int timestamp) {
int index = timestamp % 300;
if (timestamps[index] != timestamp) {
timestamps[index] = timestamp;
hits[index] = 1;
} else {
hits[index]++;
}
}
public int getHits(int timestamp) {
int total = 0;
for (int i = 0; i < 300; i++) {
if (timestamp - timestamps[i] < 300) {
total += hits[i];
}
}
return total;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 362 (Design Hit Counter)?
This page provides optimized solutions for LeetCode problem 362 (Design Hit Counter) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 362 (Design Hit Counter)?
The time complexity for LeetCode 362 (Design Hit Counter) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 362 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 362 in Java, C++, or Python.