Hit counter over a sliding time window
I was asked this
No reports yet. Sign in to say where you were asked it.
A coding interview question asked in Uber's technical phone screen, last asked Jan 2026. It tests queues, sliding window and data structure design.
Build an in-memory counter that records events and reports how many happened in the last five minutes. Implement it for a single machine first, then discuss when to drop expired events, whether a background cleanup thread is worth it, how stale data can make answers wrong, memory under heavy traffic, and concurrency.
Interface
Unless you agree on a different interface with the interviewer, assume:
-
record(timestamp: int) -> None— records one event attimestamp, in seconds. -
count(timestamp: int) -> int— the number of events with timestamps in[timestamp - 299, timestamp]. - Timestamps passed to both calls never decrease.
Example
record(1); record(2); record(3)
record(300)
count(300) -> 4 # window [1, 300]
count(301) -> 3 # window [2, 301], the event at 1 has expired
count(302) -> 2
count(599) -> 1 # only the event at 300 is left
Constraints
- Up to 10^7 events per second at peak; many events can share one timestamp.
-
countmay be called often.
Clarifying questions
- Are timestamps in seconds, and do they arrive in order?
- How many events per second? Is per-second precision enough?
- Is the window always 300 seconds, or configurable?
- Will several threads call
recordandcountat once?
What a strong answer covers
- A first version: a queue of timestamps, popping expired ones on each call. Correct, but memory grows with traffic.
- The fixed-size version: 300 buckets indexed by
timestamp % 300, each holding the second it belongs to and a count; a bucket from an old second is reset when reused. O(1) perrecord, O(300) percount(or O(1) with a running total), and constant memory. - Expiry policy: lazy cleanup on each call versus a background thread, and why lazy is usually enough here; how a stale bucket that was never reset would give a wrong count.
- Concurrency: a lock per counter, striped counters, or atomic increments per bucket, and the cost of each under contention.
- Tests: window edges, gaps longer than 300 seconds, bursts in one second.
Follow-ups
- Timestamps can arrive up to 10 seconds late. What changes?
- Count per user for millions of users. What does memory look like now?
- Turn the counter into a rate limiter that rejects a call when the last five minutes hold too many events.
- Count across several machines behind a load balancer.
Where it's asked
- Uber · Technical phone screen · Last asked Jan 202660 min · One medium problem with a follow-up, or two short ones; sometimes object-oriented design
What it tests
queues · sliding window · data structure design
No official answer yet. Write yours on the right and run it.
Nothing published yet.
Sign in to submit your code; every attempt is kept here.
