00:00

Problem Statement

Input/Output Examples

Visual Explanation

This lazy refill needs no timer thread: one subtraction, one minimum and one comparison per request.

Approaches

Both approaches implement the same token bucket and give the same answers for any sequence of requests.

Java Solutions

Each tab is a complete program that runs on Java 17 or later. Both programs print the same output for the same inputs.

Complexity Analysis

Each request does a fixed number of arithmetic steps, and the limiter stores only a few numbers per bucket, so it scales to one bucket per user or API key.

Interview Tips and Recommended Approach

  • Compare the algorithms: token bucket allows bursts; leaky bucket smooths them; fixed windows allow double bursts at window edges.
  • Refill lazily. A timer thread per bucket does not scale to thousands of users.
  • Make tryAcquire() synchronized or use an atomic compare-and-set; two threads must not spend the same token.
  • For many servers, keep the bucket in a shared store such as Redis and update it atomically.

Recommended Approach: Credit in Milliseconds

Why: it stores a single number, uses only integer maths and cannot drift, which makes it easy to reason about and to test with a fake clock.