KatInterview

Count Requests Within a Sliding Time Window

Data Structure DesignAuto-graded · 17 test cases
EasyAuto-gradedData Structure Designdata structuressliding windowrate limiter

Last updated

Tests ability to implement a sliding-window rate limiter by counting how many past requests fall within a fixed-duration window ending at each query timestamp.

Sliding-Window Request Counter

You are building a simple rate-limiter component. Given a log of request timestamps and a window size, determine how many prior requests (including the current one) are within the window for each request.

Task

Implement count_requests_in_window(timestamps, window) that takes:

  • timestamps — a non-decreasing list of integers, where each integer represents the arrival time of a request (in seconds). The same second may appear more than once.
  • window — a positive integer representing the duration of the sliding window in seconds.

For each request at position i (0-indexed), count how many requests in timestamps[0..i] (inclusive) have a timestamp t satisfying:

timestamps[i] - window < t <= timestamps[i]

In other words, the window is left-exclusive, right-inclusive: it covers the half-open interval (timestamps[i] - window, timestamps[i]].

Return a list of integers of the same length as timestamps, where element i is the count for request i.

Constraints

  • 0 <= len(timestamps) <= 2000
  • 0 <= timestamps[i] <= 10^9
  • timestamps is non-decreasing (i.e. timestamps[i] <= timestamps[i+1])
  • 1 <= window <= 10^9
  • If timestamps is empty, return an empty list.

Examples

Example 1

Input: count_requests_in_window([1, 2, 3, 4, 5], 3)

Output: [1, 2, 3, 3, 3]

Example 2

Input: count_requests_in_window([10, 10, 10, 10], 1)

Output: [1, 2, 3, 4]

Example 3

Input: count_requests_in_window([], 5)

Output: []

Hints

Hint 1

For each index i, you need the leftmost index j such that timestamps[j] > timestamps[i] - window; the answer is i - j + 1.

Hint 2

Because timestamps is non-decreasing, you can use binary search (bisect_right) to find that leftmost index efficiently.

Hint 3

Alternatively, a two-pointer approach works: advance a left pointer whenever timestamps[left] <= timestamps[i] - window.