TobilobaCodes – LeetCode Explorer

2622. Cache With Time Limit

In this challenge, you must implement a time-based cache. Each key-value pair has an associated expiration duration, after which it becomes inaccessible.

📄 Problem Statement

Write a class that allows getting and setting key-value pairs, however a time until expiration is associated with each key.

The class has three public methods:

💡 Example

Input:


const cache = new TimeLimitedCache();

cache.set(1, 42, 100); // false
cache.get(1);          // 42
cache.count();         // 1

setTimeout(() => {
  console.log(cache.get(1));  // -1
  console.log(cache.count()); // 0
}, 150);

Output:

false, 42, 1, -1, 0

🧠 Explanation

We store each key along with its value and expiration timestamp. The set method updates or adds a key with a new value and duration. The get method checks if the key exists and hasn't expired. The count method filters out all expired keys and returns the number of still-active ones.

Cleanup happens on-demand during get and count, ensuring memory stays efficient without needing extra timers.

✅ Your Solution


class TimeLimitedCache {
  constructor() {
    this.cache = new Map();
  }

  set(key, value, duration) {
    const now = Date.now();
    const exists = this.cache.has(key) && this.cache.get(key).expire > now;

    this.cache.set(key, {
      value,
      expire: now + duration
    });

    return exists;
  }

  get(key) {
    const now = Date.now();
    if (this.cache.has(key)) {
      const entry = this.cache.get(key);
      if (entry.expire > now) return entry.value;
      this.cache.delete(key);
    }
    return -1;
  }

  count() {
    const now = Date.now();
    let total = 0;
    for (const [key, { expire }] of this.cache) {
      if (expire > now) {
        total++;
      } else {
        this.cache.delete(key);
      }
    }
    return total;
  }
}