Hit Counter

Write the code, see it run, pass the checks.

The problem

  • medium
  • Code
  • Pro

Write a class HitCounter, made with new HitCounter(). hit(timestamp) records one hit at that second, and getHits(timestamp) returns how many hits came in the last 300 seconds: from timestamp − 299 to timestamp, both included. Timestamps are whole numbers from 1 up and never go down from one call to the next, hits and queries alike; several hits can share a second. For example, after hits at 1, 2 and 300, getHits(300) is 3 and getHits(301) is 2. The checks make 100,000 hits and 20,000 queries, with 60,000 hits in the window at a time, so scanning the stored hits on each query is too slow.

Your code must pass

  • Counts hits in the last 300 seconds
  • Stops counting a hit after 300 seconds
  • Counts several hits in the same second
  • Returns 0 before any hits
  • Is fast enough for 100,000 hits