LeetCode-Design Hit Counter
Design a hit counter which counts the number of hits received in the past 5 minutes.
Each function accepts a timestamp parameter (in seconds granularity) and you may assume that calls are being made to the system in chronological order (ie, the timestamp is monotonically increasing). You may assume that the earliest timestamp starts at 1.
It is possible that several hits arrive roughly at the same time.
Example:
HitCounter counter = new HitCounter(); // hit at timestamp 1. counter.hit(1); // hit at timestamp 2. counter.hit(2); // hit at timestamp 3. counter.hit(3); // get hits at timestamp 4, should return 3. counter.getHits(4); // hit at timestamp 300. counter.hit(300); // get hits at timestamp 300, should return 4. counter.getHits(300); // get hits at timestamp 301, should return 3. counter.getHits(301);
Follow up:
What if the number of hits per second could be very large? Does your design scale?
Credits:
Special thanks to @elmirap for adding this problem and creating all test cases.
Analysis:
Since only recording 300 second, we can directly use CircularBuffer.
Solution:
1 public class HitCounter { 2 /** Initialize your data structure here. */ 3 public HitCounter() { 4 hit = new int[300]; 5 head = hit.length - 1; 6 lastCallTime = 0; 7 totalHits = 0; 8 } 9 10 public void advanceTime(int timestamp) { 11 int duration = timestamp - lastCallTime; 12 lastCallTime = timestamp; 13 14 if (duration>=300){ 15 Arrays.fill(hit,0); 16 totalHits = 0; 17 head = (head+duration) % hit.length; 18 19 return; 20 } 21 22 for (int i = 0; i < duration; i++) { 23 head = (head + 1) % hit.length; 24 totalHits -= hit[head]; 25 hit[head] = 0; 26 } 27 } 28 29 /** 30 * Record a hit. 31 * 32 * @param timestamp 33 * - The current timestamp (in seconds granularity). 34 */ 35 public void hit(int timestamp) { 36 advanceTime(timestamp); 37 hit[head]++; 38 totalHits++; 39 } 40 41 /** 42 * Return the number of hits in the past 5 minutes. 43 * 44 * @param timestamp 45 * - The current timestamp (in seconds granularity). 46 */ 47 public int getHits(int timestamp) { 48 advanceTime(timestamp); 49 return totalHits; 50 } 51 52 int[] hit; 53 int head; 54 int lastCallTime; 55 int totalHits; 56 } 57 58 /** 59 * Your HitCounter object will be instantiated and called as such: 60 * HitCounter obj = new HitCounter(); 61 * obj.hit(timestamp); 62 * int param_2 = obj.getHits(timestamp); 63 */