Design a hit counter which counts the number of hits received in the past 5 minutes (i.e., the past 300 seconds).
Your system should accept a timestamp parameter (in seconds granularity), and you may assume that calls are being made to the system in chronological order (i.e., timestamp is monotonically increasing). Several hits may arrive roughly at the same time.
Implement the HitCounter class:
HitCounter()Initializes the object of the hit counter system.void hit(int timestamp)Records a hit that happened attimestamp(in seconds). Several hits may happen at the sametimestamp.int getHits(int timestamp)Returns the number of hits in the past 5 minutes fromtimestamp(i.e., the past300seconds).
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 system in chronological order (i.e.,
timestampis monotonically increasing). - At most
300calls will be made tohitandgetHits.
Follow up: What if the number of hits per second could be huge? Does your design scale?
Companies:
Amazon, Microsoft, Databricks, Affirm, Google, Apple, Twitter, Uber, Pinterest
Related Topics:
Array, Hash Table, Binary Search, Design, Queue
Similar Questions:
// OJ: https://leetcode.com/problems/design-hit-counter/
// Author: github.com/lzl124631x
// Time:
// HitCounter: O(1)
// hit, getHits: amortized O(1)
// Space: O(N)
class HitCounter {
queue<int> q;
void clear(int timestamp) {
int start = timestamp - 300;
while (q.size() && q.front() <= start) q.pop();
}
public:
HitCounter() {}
void hit(int timestamp) {
clear(timestamp);
q.push(timestamp);
}
int getHits(int timestamp) {
clear(timestamp);
return q.size();
}
};// OJ: https://leetcode.com/problems/design-hit-counter/
// Author: github.com/lzl124631x
// Time: O(1) for all
// Space: O(300)
class HitCounter {
queue<pair<int, int>> q;
int cnt = 0;
void clear(int timestamp) {
int start = timestamp - 300;
while (q.size() && q.front().first <= start) {
cnt -= q.front().second;
q.pop();
}
}
public:
HitCounter() {}
void hit(int timestamp) {
clear(timestamp);
if (q.size() && q.front().first == timestamp) q.front().second++;
else q.emplace(timestamp, 1);
++cnt;
}
int getHits(int timestamp) {
clear(timestamp);
return cnt;
}
};