Count a server's requests over any recent window and any time range with binary search
Problem
A server logs the time of every request it receives. Operators want to ask "how many requests in the last n minutes?" for any n chosen at query time, and "how many between these two times?". Build a RequestCounter class that answers both quickly.
Timestamps are whole seconds (non-negative safe integers) and arrive in chronological order: each one is greater than or equal to the one before.
new RequestCounter(options)
optionsis optional.options.retentionSeconds, if given, must be a positive safe integer; otherwise throw aRangeError.- Without a retention limit, the counter keeps every timestamp.
- With one, each
record(t)drops every stored timestamp<= t - retentionSeconds. Queries only see what is still stored.
record(timestamp)
- Stores one request. Several requests may share a timestamp.
- Throw a
TypeErroriftimestampis not a non-negative safe integer. - Throw a
RangeErrorif it is smaller than the last recorded timestamp. Nothing is stored in either case.
countLast(minutes, now)
- Returns how many stored requests have a time
twithnow - minutes * 60 < t <= now. minutesis any finite number>= 0, so0.5means 30 seconds.nowis optional and defaults to the last recorded timestamp (or0if nothing was recorded).
countBetween(start, end)
- Returns how many stored requests have
start <= t <= end. Both ends are included.
For both queries, throw a TypeError if an argument is not a finite number, and a RangeError if minutes < 0 or start > end.
size (a getter) is the number of timestamps currently stored.
Both queries must run in O(log n) time. A store can hold 200,000 requests and answer 200,000 queries, so scanning the stored timestamps per query is too slow.
const counter = new RequestCounter();
[10, 20, 20, 65, 125, 300].forEach((t) => counter.record(t));
counter.countLast(1, 125); // 1 (65 < t <= 125: only 125)
counter.countLast(2, 125); // 5 (5 < t <= 125)
counter.countLast(5); // 6 (now = 300, so 0 < t <= 300)
counter.countBetween(20, 125); // 4 (20, 20, 65, 125)
counter.record(5); // RangeError: earlier than 300
const recent = new RequestCounter({ retentionSeconds: 60 });
recent.record(0); recent.record(30); recent.record(61);
recent.size; // 2 (0 was dropped: 0 <= 61 - 60)Ref. UR-1535 · © UIRound · uiround.com/questions/count-a-server-s-requests-over-any-recent-window-and-any-time-range-with-binary-search
Unlock this question
Its tests and the tested solution are part of Pro.
- 2
- code listings
- 7
- edge cases
- 5
- follow-up questions
What's inside
- Tests that check your solution
- Step-by-step
- Approach
- Solution
- Complexity
- Edge cases
- Follow-up questions
- Card worldwide
- UPI and net banking in India
- One-time payment, nothing renews
Private, and saved in this browser as you type. All your notes are on My lists.