← 返回 ibm 的题目列表Sliding-Window Rate Limiter / Abuse IP Detection
类型:qbank
Maintain per-user or per-IP activity within a `t`-second window. One version returns allow/deny for each request; another returns IPs that appear more than `k` times in any window.
Requirements
Rate-limiter version:
Input: userId[i], time[i], k, and t.
Output: an integer array where 1 means request i is allowed and 0 means denied.
A request is allowed only if the user has made fewer than k accepted requests in the previous t seconds.
If a request is denied, it is not counted for future rate-limit decisions.
Abuse-IP version:
Input: arrays of IP addresses and timestamps, plus threshold k and window length t.
Output: every IP address that appears more than k times within any t-second window; return an empty array if none qualify.
Examples
ip = [1, 2, 1]
timestamp = [6, 10, 15]
k = 1
t = 10
Output: [1]
IP 1 appears twice within a 10-second window.
Notes
Maintain a deque of recent accepted timestamps per user/IP.
Before evaluating the current event, pop timestamps outside the active window.
For the allow/deny variant, append the current timestamp only when the request is accepted.
For the IP-detection variant, append every timestamp, and mark the IP when the deque size exceeds k.
Preparation
Code the per-key deque version and explicitly decide whether the window is [time - t, time] or (time - t, time]; this determines the pop condition.
Practise the distributed follow-up: Redis sorted sets or lists for per-key state, TTL cleanup, and a Lua/scripted atomic update to avoid read-modify-write races.