LeetCode 2676: Throttle Solution

Master LeetCode problem 2676 (Throttle), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

2676. Throttle

Medium

Problem Explanation

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:

Solution Code

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);
    }
}

Try It Yourself

Loading code editor...

Frequently Asked Questions

How to solve LeetCode 2676 (Throttle)?

This page provides optimized solutions for LeetCode problem 2676 (Throttle) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 2676 (Throttle)?

The time complexity for LeetCode 2676 (Throttle) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 2676 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 2676 in Java, C++, or Python.

Back to LeetCode Solutions