Python coding

Rate limiter over a sliding window

Write a class RateLimiter(limit, window) for an API: each client may make at most limit requests in any window consecutive seconds.

  • allow(client, t) handles a request from client at second t. If fewer than limit of that client's allowed requests fall at times in (t - window, t], it records this one and returns True; otherwise it returns False and records nothing.

So a request at time t - window has already left the window, and rejected requests never count against the client. Each client is limited separately. Times are non-negative integers that never decrease from one call to the next (several requests may share a second), and limit and window are at least 1. allow must take O(1) amortized time.

The tests call the provided run_limiter(limit, window, requests): it builds the limiter, sends each [client, t] in order and returns the list of answers.

Besides the tests, one large input (10,200 requests, limit 2,000) with a ~150 ms limit (scaled to your device's speed): brute force won't pass.

  • run_limiter(2, 10, [["ana",1],["ana",2],["ana",3],["ana",11],["ana",12],["ana",13]]) → [true,true,false,true,true,false]
  • run_limiter(1, 5, [["ana",0],["bo",0],["ana",4],["ana",5],["bo",3],["bo",5]]) → [true,true,false,true,false,true]
  • run_limiter(3, 4, [["x",0],["x",0],["x",0],["x",0],["x",3],["x",4],["x",4],["x",4],["x",4]]) → [true,true,true,false,false,true,true,true,false]
Ctrl/⌘ + Enter runs · Tab indents
Hint 1

Keep, for each client, the times of its allowed requests in arrival order. Only the ones inside the window matter, and they are always the newest ones.

Hint 2

Use a deque per client: pop expired times from the left, then compare its length with limit. Since time never goes back, an expired time never returns.

Solution and why it works
pythonO(1) amortized per request · O(clients × limit)
# --- your code ---
from collections import defaultdict, deque


class RateLimiter:
    def __init__(self, limit: int, window: int):
        self.limit, self.window = limit, window
        self.log = defaultdict(deque)        # client -> times of its allowed requests, oldest first

    def allow(self, client: str, t: int) -> bool:
        times = self.log[client]
        while times and times[0] <= t - self.window:
            times.popleft()                  # expired for good: time never goes back
        if len(times) == self.limit:
            return False                     # a rejected request is not logged
        times.append(t)
        return True


# --- provided: do not edit ---
def run_limiter(limit: int, window: int, requests: list[list]) -> list[bool]:
    limiter = RateLimiter(limit, window)
    return [limiter.allow(client, t) for client, t in requests]

This is a sliding-window log: a map from client to a deque of its allowed times. Times only grow, so expired entries are always at the left end, and each one is popped once in its life: O(1) amortized per request, with at most limit times kept per client. The traps: the window boundary (t - window is already out), logging rejected requests, which keeps a client that retries locked out, and rebuilding or rescanning the whole list on every call, O(limit) each time.