KatInterview

Request Quota Tracker with Rolling Time Windows

Data Structure DesignAuto-graded · 18 test cases
MediumAuto-gradedData Structure Designsliding-windowqueuerate-limiting

Last updated

Tests your ability to track request counts per user within a sliding time window using efficient data structures.

Problem Description

Build a request quota system that tracks whether users stay within their allowed request limits over a rolling time period. You'll process a sequence of operations that check if individual requests should be accepted or rejected.

Your function receives:

  • max_requests: the maximum number of requests a user can make within the time window
  • window_size: the duration of the rolling window in seconds
  • operations: a list of operation names (all will be "allow_request")
  • arguments: corresponding arguments for each operation

Each allow_request operation provides:

  • user_id (string): identifier for the user making the request
  • timestamp (integer): the time of the request in seconds since epoch

For each allow_request operation, determine whether the request should be allowed based on how many requests that user has made in the time interval [timestamp - window_size, timestamp] (inclusive on both ends).

Important rules:

  • Only accepted requests count toward the limit
  • Rejected requests do not consume quota
  • The time window includes both boundary timestamps
  • Each user is tracked independently

Return a list of boolean values, one per operation, indicating whether each request was allowed.

Constraints

  • 0 ≤ max_requests ≤ 1000
  • 1 ≤ window_size ≤ 10000
  • 1 ≤ len(operations) ≤ 10000
  • All operations are "allow_request"
  • Timestamps are non-negative integers
  • Timestamps for the same user appear in non-decreasing order
  • user_id is a non-empty string

Examples

Example 1

Input: track_request_quota(2, 5, ['allow_request', 'allow_request', 'allow_request', 'allow_request'], [['user1', 1], ['user1', 2], ['user1', 3], ['user1', 7]])

Output: [True, True, False, True]

Example 2

Input: track_request_quota(3, 60, ['allow_request', 'allow_request', 'allow_request', 'allow_request'], [['alice', 100], ['bob', 100], ['alice', 120], ['alice', 160]])

Output: [True, True, True, True]

Example 3

Input: track_request_quota(1, 10, ['allow_request', 'allow_request', 'allow_request'], [['u', 0], ['u', 0], ['u', 10]])

Output: [True, False, False]

Hints

Hint 1

Think about which data structure efficiently maintains timestamps in chronological order while allowing removal from the front

Hint 2

Only requests that were accepted need to be remembered - rejected requests don't affect future decisions

Hint 3

The window boundaries are inclusive, so a timestamp exactly equal to (current_time - window_size) should still count