Problem overview
A rate limiter stops a user from making too many calls in a short time. You write the class RateLimiter. The constructor new RateLimiter(limit, window) sets the rule: each user may make limit calls in any window seconds. The method allow(user, time) reports a call by user at second time and returns true if it is allowed, false if it is refused.
The call looks back over a window that starts just after second time - window and ends with second time. With a window of 10, a call at second 11 looks at seconds 2 to 11. The call is allowed when the user made fewer than limit allowed calls in that window. An allowed call counts for later calls, and a refused call does not. Each user has their own count, and the times never go down from one call to the next.
Take new RateLimiter(2, 10). Ana calls at seconds 1 and 5, and both are allowed. At second 8 she is at her limit of 2, so that call is refused. Bob's call at second 8 is allowed, because he has his own count. At second 11 the window is seconds 2 to 11, so Ana's call at second 1 has left it, and the call is allowed. At second 12 the calls at 5 and 11 are both in the window, so it is refused. The results are true true false true true false; the tests print them as True and False.
Approach: a queue of allowed call times for each user
The simple solution stores every call a user made and, on each new call, counts how many fall inside the window. That is O(n) per call for n past calls, and with 100,000 calls on one limiter it is too slow. The statement asks for O(1) amortized time.
The key observation is that times never go down. For one user, the allowed calls are stored in the order they happened, so the oldest is always the first. When a new call arrives at time, the calls that have left the window are exactly the ones at the front with a time of time - window or earlier. Those can never matter again, because later calls have even later windows. So the limiter drops them from the front, and what remains is exactly the user's allowed calls in the window. The size of the queue is then the count.
The queue is a Deque<Integer> implemented by ArrayDeque: it gives peek() for the oldest time, poll() to drop it and add to append the newest. A HashMap from user name to queue gives every user a separate count.
Why is this O(1) amortized? A single call may drop many old times, but each time is added once and dropped at most once. Over all calls, the total dropping work is at most the total number of adds, so the average work per call is constant.
Step by step
- Declare the private fields
limitandwindow, and the mapcallsfrom user to a queue of times. - The constructor stores both parameters with
this.limitandthis.window. - In
allow, create an empty queue for a user seen for the first time. - Take the user's queue into the variable
times. - While the queue is not empty and its oldest time is at most
time - window, drop the oldest time. The window starts aftertime - window, so a call made exactly at that second is already out. - If the queue now holds fewer than
limittimes, the call is allowed: addtimeto the queue and returntrue. - Otherwise return
false, without adding anything.
The solution in Java
class RateLimiter {
private int limit;
private int window;
private Map<String, Deque<Integer>> calls = new HashMap<>();
public RateLimiter(int limit, int window) {
this.limit = limit;
this.window = window;
}
public boolean allow(String user, int time) {
if (!calls.containsKey(user)) {
calls.put(user, new ArrayDeque<>());
}
Deque<Integer> times = calls.get(user);
while (!times.isEmpty() && times.peek() <= time - window) {
times.poll();
}
if (times.size() < limit) {
times.add(time);
return true;
}
return false;
}
}
The Java details worth a closer look:
timesis the same object as the map's queue.calls.get(user)returns a reference, sopoll()andaddontimeschange what the map keeps. Noputis needed afterwards.times.peek() <= time - windowcompares anIntegerfrom the queue with anint; Java unboxes it for the comparison. The!times.isEmpty()test comes first, and&&skips the second test when the first is false, becausepeek()on an empty queue returnsnull, and unboxing that would throw aNullPointerException.- No overflow here.
timeandwindoware at most 1,000,000,000, sotime - windowstays between -1,000,000,000 and 1,000,000,000, inside the range of anint(about 2.1 billion). Adding them instead could pass that range. containsKeyand thenput. A user's first call has no queue, so one is created. Later calls skip theput.
Complexity
Each call does one map lookup, drops some old times from the front, and adds at most one time. Every time is dropped at most once, so the cost per call is O(1) amortized. The space is the total number of times still queued: at most limit per user, plus the times that have not been dropped yet because their user has not called again.
Edge cases and common mistakes
- Window boundary. At second 3 with a window of 3, the window is seconds 1 to 3. A call at second 0 is out. Using
<instead of<=when dropping would keep it and refuse a call that should be allowed. Withnew RateLimiter(1, 3), the calls at seconds 0, 2, 3 and 3 givetrue false true false. - Adding refused calls. If a refused call were stored, a user who keeps trying could never get back in. Only allowed calls go in the queue.
- Calls in the same second. They all count. With
new RateLimiter(3, 100), four calls by Kim at second 50 givetrue true true false. - One shared queue. A single queue for all users would make Bob's calls count against Ana. Each user gets a queue of their own, and Lee's call at second 50 is allowed after Kim's refusal.
- Dropping before counting. The order matters: drop the old times first, then compare the size with the limit. Counting first would include calls that have already left the window.
- Time in the window versus the limit. Kim's call at second 149 is refused, because the three calls at second 50 are still inside seconds 50 to 149. At second 150 the window is seconds 51 to 150, so the call is allowed.
Testing
RateLimiter r = new RateLimiter(3, 100);
System.out.println(r.allow("kim", 50));
System.out.println(r.allow("kim", 50));
System.out.println(r.allow("kim", 50));
System.out.println(r.allow("kim", 50));
System.out.println(r.allow("lee", 50));
System.out.println(r.allow("kim", 149));
System.out.println(r.allow("kim", 150));
This prints true, true, true, false, true, false, true. The fourth call is over Kim's limit, Lee has her own count, the call at 149 still sees the three calls at 50, and the call at 150 does not.
