KatInterview

Sliding Window API Rate Limiter

Data Structure DesignAuto-graded · 17 test cases
EasyAuto-gradedData Structure Designrate limitersliding windowdata structures

Last updated

Tests ability to implement a sliding-window rate limiter that counts requests within a fixed-width time window using a list of timestamps.

Sliding Window API Rate Limiter

You are building a lightweight API gateway. To protect a service, you must enforce a sliding-window rate limit: for each incoming request, decide whether it should be allowed or denied based on how many requests have already been made in the most recent window.

Task

Implement the function check_requests that, given a chronological log of request timestamps and a rate-limit configuration, returns a list of decisions ("allow" or "deny") — one per request, in order.

Rate-limit rule:
A request at time t is allowed if the number of previously allowed requests with timestamps in the half-open interval (t - window_size, t] (i.e., strictly after t - window_size and up to and including t) is strictly less than max_requests. If that count equals or exceeds max_requests, the request is denied.

Important: Denied requests do not count toward the limit — only allowed requests consume quota.

Parameters

NameTypeDescription
timestampsList[int]Arrival times of requests in non-decreasing order (seconds).
window_sizeintWidth of the sliding window in seconds (≥ 1).
max_requestsintMaximum allowed requests permitted inside the window (≥ 1).

Returns

List[str] — A list of "allow" or "deny" strings, one per request, in the same order as timestamps.

Constraints

  • 0 ≤ len(timestamps) ≤ 2000
  • timestamps is non-decreasing: timestamps[i] ≤ timestamps[i+1]
  • 0 ≤ timestamps[i] ≤ 10^9
  • 1 ≤ window_size � 10^9
  • 1 ≤ max_requests ≤ 2000
  • If timestamps is empty, return an empty list.

Examples

Example 1

Input: check_requests([1, 1, 1, 2, 3], 2, 2)

Output: ['allow', 'allow', 'deny', 'deny', 'allow']

Example 2

Input: check_requests([10, 20, 30, 40, 50], 15, 3)

Output: ['allow', 'allow', 'allow', 'allow', 'allow']

Example 3

Input: check_requests([], 10, 5)

Output: []

Hints

Hint 1

Keep a running list (or deque) of timestamps for requests that were allowed, and trim it as the window slides forward with each new request.

Hint 2

For each new request at time t, remove all allowed timestamps that are ≤ t - window_size before checking the count against max_requests.

Hint 3

You only add a timestamp to the allowed list when the decision is 'allow' — denied requests must be invisible to the rate limiter.