Cache With Time Limit

ClassesTimersData Structures

Build a TimeLimitedCache class with three methods:

  • set(key, value, duration) stores the pair for duration ms and returns whether an unexpired entry for that key already existed.
  • get(key) returns the value if it is still alive, otherwise -1.
  • count() returns how many entries are currently alive.

Examples

Example 1
Input
const cache = new TimeLimitedCache();
cache.set(1, 42, 100);  // false
cache.get(1);           // 42
// 150ms later
cache.get(1);
Output
-1
Explanation
The entry expired 50ms ago, so get reports a miss.

Constraints

  • 0 <= key, value <= 10^9
  • 0 <= duration <= 1000
  • At most 100 calls

Notes

  • Setting an existing key must clear the previous timer, or the earlier timeout deletes an entry that was just refreshed.

Hints

Read the full write-up for Cache With Time Limit
</>JavaScript
Loading editor…
Test Result
Run your code, or Submit to test it