Sign in to devexcode.com with google.com

To continue, google.com will share your name, email address, and profile picture with this site. See this site's privacy policy.

2676. Throttle

Explanation:

The problem requires implementing a throttling mechanism to limit the number of requests within a given time frame. The rules for throttling are as follows:

  1. No more than 3 requests are allowed in any 5-second window.
  2. No more than 20 requests are allowed in any 10-second window.
  3. No more than 60 requests are allowed in any 1-minute window.

The algorithm involves maintaining a sliding window for each time frame and counting the number of requests that fall within each window. By keeping track of the timestamps of each request, we can efficiently update the window boundaries and maintain the request count. Solution:

import java.util.HashMap;
import java.util.Map;

class Throttle {
    private Map<Integer, Integer> requests;

    public Throttle() {
        this.requests = new HashMap<>();
    }

    public boolean isThrottled(int timestamp) {
        cleanUp(timestamp);
        if (requests.size() >= 60) return true;
        if (requests.size() >= 20 && timestamp - requests.keySet().iterator().next() < 10) return true;
        if (requests.size() >= 3 && timestamp - requests.keySet().iterator().next() < 5) return true;
        return false;
    }

    public void addRequest(int timestamp) {
        cleanUp(timestamp);
        requests.put(timestamp, 1);
    }

    private void cleanUp(int timestamp) {
        requests.entrySet().removeIf(entry -> timestamp - entry.getKey() >= 60);
    }
}

Code Editor (Testing phase)

Improve Your Solution

Use the editor below to refine the provided solution. Select a programming language and try the following:

  • Add import statement if required.
  • Optimize the code for better time or space complexity.
  • Add test cases to validate edge cases and common scenarios.
  • Handle error conditions or invalid inputs gracefully.
  • Experiment with alternative approaches to deepen your understanding.

Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.