MediumDesignQueueBinary Search

Design Hit Counter

LeetCode
1 approach, code in all languages

Design a counter that records hits and, at any moment, can report how many hits occurred during the most recent five-minute window. Time is measured in seconds, and calls arrive in non-decreasing timestamp order.

Implement the class HitCounter. hit(timestamp) records that a hit happened at the given time in seconds. getHits(timestamp) returns the number of hits that occurred in the previous 300 seconds, meaning every recorded time t with timestamp minus 300 strictly less than t and t less than or equal to timestamp.

Several hits may share the same timestamp, and every hit must be counted individually.

Example 1

Input: operations = ["HitCounter", "hit", "hit", "hit", "getHits", "hit", "getHits", "getHits"] args = [[], [1], [2], [3], [4], [300], [300], [301]]

Output: [null, null, null, null, 3, null, 4, 3]

Hits at seconds 1, 2, and 3 give getHits(4) = 3. A hit at 300 makes getHits(300) = 4 since all four are within the window. By second 301 the hit at second 1 has expired, leaving 3.

Example 2

Input: operations = ["HitCounter", "hit", "getHits", "getHits"] args = [[], [1], [100], [400]]

Output: [null, null, 1, 0]

The single hit at second 1 is still counted at second 100, but by second 400 it has fallen outside the 300-second window.

Constraints

  • 1 <= timestamp <= 2 * 10^9
  • All calls are made with a non-decreasing value of timestamp.
  • At most 300 calls will be made to hit and getHits.
You've got the patterns

Patterns get you through the screen. Shipping gets you hired.

FDE Coach is a cohort-based program in frontend, backend, AWS, and AI where you build real products and get referred to 200+ hiring partners. The free live workshop is the fastest way to see how we teach.

750+ engineers trained · frontend, backend, AWS & AI

August 15 · 0d left
Enroll Now