iq.lab
Python starts when a code cell comes near or you run one
mediumDesign as codingQueues and deques target 25 min

Hit counter

Build a class HitCounter that records events, called hits, and answers one question: how many hits happened in the 300 seconds (5 minutes) up to a given second?

  • HitCounter() starts with no hits.
  • hit(timestamp) records one hit at second timestamp.
  • get_hits(timestamp) returns how many recorded hits have a time t with timestamp - 300 < t ≤ timestamp. So a hit exactly 300 seconds old no longer counts. Asking records nothing.

Calls arrive in time order: each call's timestamp is at least the previous call's. Many hits can arrive in the same second. (LeetCode spells the second method getHits.)

Example 1
Inputhit(5), hit(9), hit(9), get_hits(10), hit(120), get_hits(304), get_hits(305), get_hits(309)Outputthe four get_hits calls return 3, 4, 3, 1

At second 305 the hit from second 5 is 300 seconds old and drops out. At 309 both hits from second 9 drop out too.

Example 2
Inputhit(10), hit(20), get_hits(309), get_hits(310), get_hits(1000)Outputthe three get_hits calls return 2, 1, 0

At 310 the hit from second 10 is exactly 300 seconds old. By 1000 every hit is too old.

Constraints
  • 1 ≤ timestamp ≤ 2 × 109

  • Timestamps never decrease from one call to the next.

  • Up to 105 calls in total; many hits can share one second.

Plan it first

Write a line for each before you code, then say them out loud. Compare with the Approach tab afterwards.

⌘+Enter runs 0:00Python starts when a code cell comes near or you run one
Run examples checks the examples. Submit runs every test, including edge cases and, when the problem has one, a speed check on a large input.