← Google bank

Google · Question 48 · Queues

Design Hit Counter

QueuesPythoncode⏱ O(1)💾 O(n)
Product-based

Problem

Count hits received in the past 5 minutes.

Approach

Store timestamps in a queue and remove outdated ones.

Time O(1)Space O(n)

How it works

  1. 1Record hit timestamps in a queue.
  2. 2Remove hits older than 300 seconds on query.
  3. 3Return the number of hits in the last 5 minutes.

Sample input / output

Input:
7
hit 1
hit 2
hit 3
getHits 4
hit 300
getHits 300
getHits 301
Output:
[3, 4, 3]

Constraints

1 <= timestamp <= 2 * 10^9; single-threaded; at most 300 calls per test.

Solution — read it, then walk it

Time O(1)Space O(n)Loops 2Branches 3Returns 1source · Python
Scroll sideways for wide charts — the view follows the active step.
↻ repeatyesno↻ repeatyesnoSTARTfrom collections importdequeCLASS HitCounterDEFINE __init__(self)self.hits = deque()DEFINE hit(self, timestamp)self.hits.append(timestamp)DEFINE getHits(self,timestamp)while self.hits andself.hits[0] <=timestamp - 300self.hits.popleft()RETURN len(self.hits)DEFINE main()import sysdata =sys.stdin.read().split()it = iter(data)ops = int(next(it))hc = HitCounter()out = []for _ in range(ops)op = next(it)if op == 'hit'hc.hit(int(next(it)))ELSEout.append(hc.getHits(int(next(it))))print(out)if __name__ =="__main__"main()END
  • start / end
  • statement
  • condition
  • loop
  • returns
  • definition
1/27

StartSTART

Interactive control-flow diagram and step-by-step code walkthrough.

Recommended resourcesAffiliate links · may earn us a commission

Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits