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 your may assume that calls is being made to the S Ystem in chronological order (ie, the timestamp is monotonically increasing). Assume the earliest timestamp starts at 1.
It is possible this several hits arrive roughly at the same time.
Example:
Follow up:
What if the number of hits per second could is very large? Does your design scale?
Credits:
Special thanks to @elmirap for adding this problem and creating all test cases.
Public classHitCounter {PrivateHashmap<integer, integer>map; /**Initialize your data structure here.*/ PublicHitCounter () {map=NewHashmap<integer, integer>(); } /**Record a hit. @paramtimestamp-the current timestamp (in seconds granularity).*/ Public voidHitinttimestamp) { if(Map.containskey (timestamp)) {Map.put (Timestamp,map.get (timestamp) )+1); } Else{map.put (timestamp,1); } } /**Return the number of hits in the past 5 minutes. @paramtimestamp-the current timestamp (in seconds granularity).*/ Public intGethits (inttimestamp) { intBegin = Timestamp-300; intsum = 0; for(intKey:map.keySet ()) { if(key>begin&&key<=timestamp) {Sum= Sum +Map.get (key); } } returnsum; }}/*** Your HitCounter object would be instantiated and called as such: * hitcounter obj = new HitCounter (); * Obj.hit (Time Stamp); * int param_2 = obj.gethits (timestamp); */
Design hit Counter