KatInterview

Sliding-Window Rate Limiter Over Event Timestamps

Data Structure DesignAuto-graded · 16 test cases
MediumAuto-gradedData Structure Designdata structuresrate limitersliding window

Last updated

Tests the ability to implement a sliding-window rate limiter that, given a log of request timestamps, determines which requests are allowed under a fixed-window capacity.

Sliding-Window Rate Limiter Over Event Timestamps

You are building the core logic for a sliding-window rate limiter.

Given a chronological log of request timestamps and a rate-limit configuration, decide which requests are allowed and which are rejected.

How the rate limiter works

  • The limiter allows at most limit requests within any sliding window of window_ms milliseconds.
  • Requests are processed in the order they appear in the log.
  • When a request arrives at time t, count how many previously allowed requests have a timestamp in the half-open interval (t - window_ms, t] (i.e., strictly greater than t - window_ms and at most t).
    • If that count is strictly less than limit, the current request is allowed (count it going forward).
    • Otherwise, it is rejected (do not count it going forward).
  • Timestamps in timestamps are non-decreasing (requests arrive in order, ties allowed).
  • Each element of timestamps corresponds to one request; process them left to right.

Your task

Implement the function:

def rate_limiter(timestamps: List[int], limit: int, window_ms: int) -> List[bool]

Return a list of booleans of the same length as timestamps, where True means the request was allowed and False means it was rejected.

Constraints

  • 0 ≤ len(timestamps) ≤ 2000
  • 0 ≤ timestamps[i] ≤ 10^9; the list is non-decreasing
  • 1 ≤ limit ≤ 2000
  • 1 ≤ window_ms ≤ 10^9
  • If timestamps is empty, return an empty list.
  • Ties (equal timestamps): each is treated as a separate request and processed in order.

Examples

Example 1

Input: rate_limiter([100, 200, 300, 400, 500], 3, 300)

Output: [True, True, True, True, True]

Example 2

Input: rate_limiter([0, 0, 0, 0], 2, 1000)

Output: [True, True, False, False]

Example 3

Input: rate_limiter([1000, 2000, 3000], 1, 500)

Output: [True, True, True]

Hints

Hint 1

Use a queue (or deque) to track the timestamps of only the allowed requests; on each new request, evict entries that fall outside the sliding window before checking the count.

Hint 2

The window is (t - window_ms, t], so evict any allowed-request timestamp that is ≤ t - window_ms.

Hint 3

You never need to store rejected timestamps — only allowed ones affect future decisions.