Problem · Array

Simulate a Queued Multi-Rule Rate Limiter

Learn this problem
MediumSnowflake logoSnowflakeFULLTIMEPHONE SCREEN
See Snowflake hiring insights

Problem statement

Simulate a serialized, thread-safe rate limiter over a finite FIFO request stream.

Each request is [arrivalTime,successFlag]. Requests arrive in nondecreasing time order and join one FIFO queue; equal-time requests preserve input order. A successFlag of 1 means its handler succeeds, and 0 means the handler throws.

Each rule is [limit,window]. For this exercise, assume a rule permits at most limit successful handler executions in the rolling half-open interval (time - window,time]. Therefore, a success processed at time s frees its slot exactly at s + window. Every rule must have capacity before the request at the front of the queue may invoke its handler.

Handlers run atomically in FIFO order. A failed handler still waits for capacity before it runs, but after it throws it consumes no slot in any rule. A successful handler consumes one slot in every rule.

Return each request's actual handler-start time in original input order.

Function

simulateRateLimiter(requests: int[][], rules: int[][]) → long[]

Examples

Example 1

requests = [[0,1],[1,1],[2,1],[3,1],[4,1]]rules = [[2,5]]return = [0,1,5,6,10]

The first two successes occupy both slots. The third waits until time 5, when the success at time 0 expires. FIFO serialization then makes the fourth wait until 6 and the fifth until 10.

Example 2

requests = [[0,1],[1,0],[2,1],[3,1]]rules = [[2,10]]return = [0,1,2,10]

The handler at time 1 throws and consumes no slot. The successful requests at 0 and 2 fill the rule, so the last request waits until the first slot frees at time 10.

Example 3

requests = [[0,1],[1,1],[2,1],[3,1]]rules = [[2,5],[3,10]]return = [0,1,5,10]

The 5-second rule delays the third request to time 5. At that point the 10-second rule contains three successes, so the fourth request cannot run at time 6; it waits until time 10.

Constraints

  • 0 <= requests.length <= 200000
  • Every request is [arrivalTime,successFlag], arrival times are nondecreasing nonnegative integers, and successFlag is 0 or 1.
  • 1 <= rules.length <= 10
  • Every rule is [limit,window] with 1 <= limit <= 200000 and 1 <= window <= 10^9.
  • Every returned processing time fits in a signed 64-bit integer.

More Snowflake problems

drafts saved locally
public long[] simulateRateLimiter(int[][] requests, int[][] rules) {
    // Write your code here.
}
requests[[0,1],[1,1],[2,1],[3,1],[4,1]]
rules[[2,5]]
expected[0,1,5,6,10]
checking account