MediumDesignQueueBinary Search

1 approach, code in every language

Problem description

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.

After the pattern

Now solve one you haven't seen.

Reading a pattern isn't the same as using it. The practice set has 1,194 original problems on the same techniques, each graded in your browser.

1,194 problems · 15,062 graded tests · free