17 · Queues & Deques

#362 Design Hit Counter

frequently reported atAppleUberWalmartGoogleAmazon

the problem

In plain words

You're building the live "requests in the last 5 minutes" number on a web server's dashboard. Implement HitCounter: hit(timestamp) records one request at that second, and getHits(timestamp) returns how many requests arrived in the last 300 seconds — timestamps in the range (timestamp − 300, timestamp]. Calls come in non-decreasing time order, and many hits can share the same second.

in hit(2), hit(2), hit(150), getHits(150), hit(301), getHits(301), getHits(302), getHits(450), getHits(601)

out 3, 4, 2, 1, 0

At 302 the window is (2, 302], so both hits at second 2 have expired. At 601 it is (301, 601] — even the hit at 301 is out.

  • 1 ≤ timestamp ≤ 2·10⁹
  • Calls arrive in non-decreasing timestamp order
  • Several hits can share one timestamp
  • At most 300 calls in total (follow-up: what if there are millions of hits per second?)

your turn

Try it before you peek

Read the examples, say the brute force out loud, then write code right here. Stuck for 20 minutes? Open one hint at a time.

This one is LeetCode Premium. You don't need a subscription: solve it right here. The free alternative linked above is the closest free practice; its label says how close it is.

Solve it in the browser

Design: implement every operation. Compiled by the real javac (Java 17) and judged right here — nothing is sent anywhere.

    Solutions are hidden so you can try first. Even 20 minutes of real effort makes the answer stick far better than reading it.

    Marking the problem solved, or opening every hint, also shows it.

    practise next

    Similar problems

    1. #933
    2. #622
      Design Circular Queue
      Mediumin Queues
    3. #146
      LRU Cache
      Mediumin Linked Lists