LeetCode 2622: Cache With Time Limit Solution

Master LeetCode problem 2622 (Cache With Time Limit), 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.

2622. Cache With Time Limit

Medium

Problem Explanation

Explanation

To implement the cache with time limit, we can use a HashMap to store key-value pairs along with their expiration times. When setting a key-value pair, we update the HashMap with the new value and expiration time. When getting a value, we check if the key exists and if it has not expired. When counting, we iterate through the HashMap and count the unexpired keys.

Solution Code

import java.util.HashMap;

class TimeLimitedCache {
    private HashMap<Integer, Integer> cache;
    private HashMap<Integer, Integer> expiration;

    public TimeLimitedCache() {
        cache = new HashMap<>();
        expiration = new HashMap<>();
    }

    public boolean set(int key, int value, int duration) {
        if (expiration.containsKey(key) && System.currentTimeMillis() < expiration.get(key)) {
            cache.put(key, value);
            expiration.put(key, System.currentTimeMillis() + duration);
            return true;
        } else {
            cache.put(key, value);
            expiration.put(key, System.currentTimeMillis() + duration);
            return false;
        }
    }

    public int get(int key) {
        if (cache.containsKey(key) && System.currentTimeMillis() < expiration.get(key)) {
            return cache.get(key);
        } else {
            return -1;
        }
    }

    public int count() {
        int count = 0;
        for (int key : expiration.keySet()) {
            if (System.currentTimeMillis() < expiration.get(key)) {
                count++;
            }
        }
        return count;
    }
}

Try It Yourself

Loading code editor...

Frequently Asked Questions

How to solve LeetCode 2622 (Cache With Time Limit)?

This page provides optimized solutions for LeetCode problem 2622 (Cache With Time Limit) 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 2622 (Cache With Time Limit)?

The time complexity for LeetCode 2622 (Cache With Time Limit) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 2622 on DevExCode?

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

Back to LeetCode Solutions