KatInterview

Admit or Deny Requests Under a Per-Client Rolling Quota

Data Structure DesignAuto-graded · 19 test cases
MediumAuto-gradedData Structure Designsliding-windowdequehash-map

Last updated

Process a time-ordered request log and decide per request whether a client is under its quota in a rolling time window, counting only previously admitted requests.

A server reads a log of incoming requests in order. The i-th request occurs at time arrival_times[i] and comes from the client address client_ids[i]. Each client is allowed at most max_requests admitted requests within any rolling period of length period. For every request, in log order, decide whether it is admitted (1) or denied (0).

Rules

  • Handle requests in index order 0, 1, ..., n - 1. Times never decrease along the log, and requests sharing the same time are handled in index order.
  • For request i at time t = arrival_times[i] from client c, count the earlier requests j < i that satisfy all of the following:
    • client_ids[j] == c,
    • request j was admitted,
    • arrival_times[j] > t - period.
  • A request made exactly at time t - period is outside the period and is not counted.
  • If the count is strictly less than max_requests, admit request i (output 1). Otherwise deny it (output 0).
  • Denied requests are not remembered: they never contribute to any later count.
  • Client addresses are compared as exact strings, with no normalization. Different clients never influence one another.

Return a list of length n whose i-th entry is the decision for request i.

Constraints

  • 1 <= n <= 10^5, where n = len(arrival_times) == len(client_ids)
  • 0 <= arrival_times[i] <= 10^9, and arrival_times[i] <= arrival_times[i + 1]
  • 1 <= max_requests <= 10^5
  • 1 <= period <= 10^9
  • Each client_ids[i] is a non-empty string of at most 45 characters.
  • All values fit in a 32-bit signed integer.

Examples

Example 1

Input: admit_requests([1, 2, 3, 4, 4], ['10.0.0.1', '10.0.0.1', '10.0.0.1', '10.0.0.1', '10.0.0.2'], 2, 3)

Output: [1, 1, 0, 1, 1]

Example 2

Input: admit_requests([5, 5, 5], ['192.168.1.7', '192.168.1.7', '192.168.1.7'], 1, 10)

Output: [1, 0, 0]

Example 3

Input: admit_requests([0, 10, 19, 20], ['1.1.1.1', '1.1.1.1', '1.1.1.1', '1.1.1.1'], 1, 10)

Output: [1, 1, 0, 1]

Hints

Hint 1

Only admitted requests matter for later decisions, so you only need to remember those, grouped by client.

Hint 2

Because times never decrease, the admitted times for one client are already sorted. The ones that have expired are always at the oldest end.

Hint 3

Keep a queue per client in a hash map. Before each check, drop front entries with time <= t - period, then compare the queue length to the quota and append only on admission.