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?
1 public class HitCounter { 2 private int[] times; 3 private int[] hits; 4 5 /** Initialize your data structure here. */ 6 public HitCounter() { 7 times = new int[300]; 8 hits = new int[300]; 9 }10 11 /** Record a hit.12 @param timestamp - The current timestamp (in seconds granularity). */13 public void Hit(int timestamp) {14 int index = timestamp % 300;15 if (times[index] != timestamp) {16 times[index] = timestamp;17 hits[index] = 1;18 } else {19 hits[index]++;20 }21 }22 23 /** Return the number of hits in the past 5 minutes.24 @param timestamp - The current timestamp (in seconds granularity). */25 public int GetHits(int timestamp) {26 int total = 0;27 for (int i = 0; i < 300; i++) {28 if (timestamp - times[i] < 300) {29 total += hits[i];30 }31 }32 return total;33 }34 }35 36 public class HitCounterSolution1 {37 38 // could use a queue service like SQS to scale up39 private Queue cache = new Queue ();40 41 // to scale up and ensure duralbility , this need to store in db42 // or use redis43 private int count = 0;44 45 46 /** Record a hit.47 @param timestamp - The current timestamp (in seconds granularity). */48 public void Hit(int timestamp) {49 cache.Enqueue(timestamp);50 51 // this guy doesn't guarantee atomic in a multithread environment52 // we can add lock but this would produce higher latency53 count++;54 }55 56 /** Return the number of hits in the past 5 minutes.57 @param timestamp - The current timestamp (in seconds granularity). */58 public int GetHits(int timestamp) {59 while (cache.Count > 0 && timestamp - cache.Peek() >= 300)60 {61 cache.Dequeue();62 count--;63 }64 65 return count;66 }67 }68 69 /**70 * Your HitCounter object will be instantiated and called as such:71 * HitCounter obj = new HitCounter();72 * obj.Hit(timestamp);73 * int param_2 = obj.GetHits(timestamp);74 */