Practice/Uber/Leetcode 362. Design Hit Counter
CodingMust
Build a system that tracks events (hits) as they occur and can quickly answer queries about how many events happened in the last 5 minutes (300 seconds). Your implementation should support two operations:
The system must efficiently handle high-frequency operations while maintaining accurate counts within the sliding 300-second window.
HitCounter class with a constructor and two methods: hit and getHitshit method should record an event at the specified timestampgetHits method should return the count of all events within the past 300 seconds from the query timestamphitgetHitsExample 1:
` Operations: ["HitCounter", "hit", "hit", "hit", "getHits", "hit", "getHits"] Arguments: [[], [1], [2], [3], [4], [300], [300]] Output: [null, null, null, null, 3, null, 4]
Explanation: HitCounter counter = new HitCounter(); counter.hit(1); // Record hit at timestamp 1 counter.hit(2); // Record hit at timestamp 2 counter.hit(3); // Record hit at timestamp 3 counter.getHits(4); // At time 4, all 3 hits are within [4-299, 4], return 3 counter.hit(300); // Record hit at timestamp 300 counter.getHits(300); // At time 300, all 4 hits are within [1, 300], return 4 `
Example 2:
` Operations: ["HitCounter", "hit", "hit", "hit", "getHits", "getHits"] Arguments: [[], [1], 2], [3], [4], [301]] Output: [null, null, null, null, 3, 2]
Explanation: HitCounter counter = new HitCounter(); counter.hit(1); // Record hit at timestamp 1 counter.hit(2); // Record hit at timestamp 2 counter.hit(3); // Record hit at timestamp 3 counter.getHits(4); // All 3 hits within window, return 3 counter.getHits(301); // Hit at timestamp 1 has expired (301-1=300), only hits at 2 and 3 remain, return 2 `