KatInterview

Sliding Window Request Rate Calculator

Data Structure DesignAuto-graded · 18 test cases
MediumAuto-gradedData Structure Designsliding-windowtime-seriesdata-structures

Last updated

Tests the ability to implement time-bucketed sliding-window aggregation with efficient memory usage and amortized constant-time operations.

Build an in-memory request rate tracker that processes a stream of operations.

You must handle two types of operations:

  • "record" with parameters [key, timestamp]: log that a request for the given key occurred at the specified timestamp
  • "get_qps" with parameters [key, now]: calculate and return the average requests per second for the key over a 5-minute sliding window ending at now

Specification

The sliding window spans exactly 300 seconds: [now - 299, now] inclusive at both endpoints.

The queries-per-second value is computed as: (total requests in window) / 300.0

Return results as a list in the same order as operations:

  • "record" operations produce None (or null)
  • "get_qps" operations produce a float

Behavior

  • Timestamps are non-negative integers representing seconds
  • Operations arrive in non-decreasing timestamp order
  • Multiple requests may share the same key and timestamp
  • A key with no recorded requests returns 0.0
  • A key whose requests have all expired (fallen outside the window) returns 0.0
  • The divisor is always 300.0, even when fewer than 300 seconds of data exist

Constraints

  • 1 ≤ number of operations ≤ 100,000
  • 0 ≤ timestamp ≤ 10^9
  • 1 ≤ key length ≤ 50
  • All timestamps in the operation sequence are non-decreasing

Examples

Example 1

Input: calculate_request_rates(['record', 'get_qps', 'record', 'record', 'get_qps', 'get_qps'], [['api', 100], ['api', 100], ['api', 101], ['worker', 101], ['api', 101], ['worker', 101]])

Output: [None, 0.0033333333333333335, None, None, 0.006666666666666667, 0.0033333333333333335]

Example 2

Input: calculate_request_rates(['record', 'get_qps', 'get_qps'], [['api', 1], ['api', 300], ['api', 301]])

Output: [None, 0.0033333333333333335, 0]

Hints

Hint 1

Store request counts grouped by timestamp rather than storing each individual request to save memory

Hint 2

Use a queue structure to efficiently expire old data from the front as time advances

Hint 3

Maintain a running sum of requests in the current window to avoid recounting on every query