KatInterview

Simulate Rate Limiter Decisions

Data Structure DesignAuto-graded · 19 test cases
EasyAuto-gradedData Structure Designdesignsimulationarrays

Last updated

Simulate a thread-safe fixed-window rate limiter processing a sequence of request timestamps.

You are building a simulation of a rate-limiting mechanism to evaluate how request calls are accepted or rejected over time under safe concurrent execution semantics.

The rate limiter enforces a capacity limit of limit requests per 1.0-second fixed time window:

  • The very first request timestamp sets the initial window start time (window_start).
  • For any incoming request at timestamp t, if t - window_start >= 1.0, a new 1.0-second window begins immediately with its start time set to t, and the window count resets.
  • If the current window count is strictly less than limit, the request is accepted (True), and the window count increments by 1.
  • Otherwise, the request is denied (False).

Given an integer limit and a list of float timestamps sorted in non-decreasing order representing arrival times of incoming requests, return a list of booleans indicating whether each corresponding request is accepted (True) or rejected (False).

Constraints

  • 0 <= limit <= 10^5
  • 0 <= len(timestamps) <= 10^5
  • Timestamps are non-decreasing floats: timestamps[i] <= timestamps[i+1] for all valid i.

Examples

Example 1

Input: rate_limiter_decisions(3, [0, 0.1, 0.2, 0.9, 1, 1.1])

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

Example 2

Input: rate_limiter_decisions(2, [10, 10, 10.2, 10.999, 11])

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

Example 3

Input: rate_limiter_decisions(1, [5.25, 6.25, 6.26])

Output: [True, True, False]

Example 4

Input: rate_limiter_decisions(0, [0, 0.5, 1, 2])

Output: [False, False, False, False]

Hints

Hint 1

If the timestamps list is empty, immediately return an empty list.

Hint 2

Track two state variables while iterating: the start time of the active 1-second window and the number of requests accepted in that window.

Hint 3

Check if `t - window_start >= 1.0`. If true, update `window_start = t` and reset the count to 0 before deciding whether to accept the request.