Implement a rate-limited hit counter
DatabricksSoftware Engineer · OnsiteLast updated
This question evaluates a candidate's understanding of designing efficient time-windowed data structures and algorithmic analysis, including space-time trade-offs and amortized complexity.
You are designing a hit counter that records the number of hits received in the past 5 minutes.
Implement a class HitCounter with the following methods:
void hit(int timestamp): Records a hit at the giventimestamp(in seconds). The timestamp is given in seconds granularity and is strictly increasing across all calls.int getHits(int timestamp): Returns the number of hits received in the past 5 minutes (i.e., the past 300 seconds) including the current second, at the giventimestamp.
Constraints:
1 <= timestamp <= 10^9.- Methods will be called in non-decreasing order of
timestamp. - The number of calls to both
hitandgetHitsis up to 10^5.
Describe the data structures and algorithms you would use to implement HitCounter so that both operations are efficient in time and memory. Do not write code; just specify the design and complexity.
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.