Batching and serving algorithms · Medium

Sliding Token-Budget Admission

Problem 48 of 50 · Python and NumPy

Problem

Apply an exact sliding-window token admission budget. arrivals is an ordered list of [timestamp,cost]. For an arrival at time t, expire previously accepted costs with timestamp ≤ t−window, then accept if the sum still active plus cost is ≤ budget. Rejected costs are never added.

Return one boolean per arrival. Equal timestamps are processed in input order. The active interval is (t−window,t], so costs exactly on the left boundary have expired.

def sliding_token_admission(budget, window, arrivals):

Constraints

  • 0 ≤ budget ≤128; window is a positive finite number.
  • 0..64 arrivals with finite nondecreasing timestamps and nonnegative integer costs ≤128.
  • Inputs satisfy these constraints; invalid-input handling is not graded. Use only Python standard library and NumPy.

Examples

Example 1

Arguments: [
  5,
  10,
  [
    [
      0,
      3
    ],
    [
      1,
      3
    ],
    [
      10,
      3
    ]
  ]
]
Expected result: [
  true,
  false,
  true
]

Accept cost 3 at time 0, reject the next 3, then expire the first cost at time 10 and accept again.

Example 2

Arguments: [
  5,
  10,
  [
    [
      0,
      2
    ],
    [
      0,
      3
    ],
    [
      0,
      1
    ]
  ]
]
Expected result: [
  true,
  true,
  false
]

Costs 2 and 3 exactly fill budget 5; the following cost 1 is rejected.

Sign in to solve this problem

Browse all coding problems · Learn the foundations