EasyPythonJavaScriptTypeScript
System Design — Hit Counter
System DesignQueueSliding Window
Build the counter behind a "requests in the last 5 minutes" metric.
solve(args, ops) builds new HitCounter() (no constructor arguments) and replays ops:
hit(timestamp)— record one hit attimestamp(seconds). Returns nothing.count(timestamp)— return how many hits happened in the last 300 seconds, that is
hits with timestamp - 300 < hitTime <= timestamp.
Timestamps never go backwards. Several hits can share a timestamp. Keep memory bounded: drop
hits that have left the window instead of keeping the whole history (a queue works).
Example
hit(1) hit(2) hit(3) count(4) → 3
hit(300) count(300) → 4
count(301) → 3 // the hit at t=1 has expiredSample tests
Test #1Classic example with an expiring hit
Input: [[],[["hit",1],["hit",2],["hit",3],["count",4],["hit",300],["count",300],["count",301]]]
Output: [null,null,null,3,null,4,3]
Test #2No hits yet
Input: [[],[["count",1]]]
Output: [0]
Test #3Hits sharing a timestamp expire together
Input: [[],[["hit",5],["hit",5],["hit",5],["count",5],["count",304],["count",305]]]
Output: [null,null,null,3,3,0]