362.Design Hit Counter
Problem description:
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 past300
seconds).
Example 1:
1 | Input |
Constraints:
1 <= timestamp <= 2 * 109
- All the calls are being made to the system in chronological order (i.e.,
timestamp
is monotonically increasing). - At most
300
calls will be made tohit
andgetHits
.
Follow up: What if the number of hits per second could be huge? Does your design scale?
Solution:
Two ways to implement
- Circular array
- Queue
circular array might be better in huge amount of hit count
1 | class HitCounter: |
time complexity: $O()$
space complexity: $O()$
reference:
related problem: