#Classes#Timers

Cache With Time Limit

A key/value cache where every entry expires on its own timer — and setting a key again restarts its clock.

By Pratik RaiMedium

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

Input:

JSfile.javascript
1const cache = new TimeLimitedCache(); 2cache.set(1, 42, 100); // false 3cache.get(1); // 42 4// 150ms later 5cache.get(1);

Output:

-1

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.

Goal: Every entry expires independently, and re-setting a key restarts its timer.

Source

Frequently asked questions

What is a TTL cache?
A cache where every entry carries a time to live and disappears once it elapses. It suits data that is expensive to fetch and acceptable to serve slightly stale, such as a config blob or a search suggestion list.
Should expiry be checked on read or handled by a timer?
A timer that deletes the entry keeps the map holding only live entries, so reads and counts need no filtering. Checking on read is also valid and avoids holding timers, but then every method has to know about expiry.
What happens when you set a key that already exists?
Its previous timer must be cleared first. Leave it scheduled and it will fire later and delete an entry that was just refreshed, so a key you keep updating vanishes unexpectedly.
How is this different from an LRU cache?
A TTL cache evicts by age; an LRU cache evicts by use once it hits a size limit. They solve different problems and are often combined — bounded size with a freshness guarantee.

Related Challenges

Continue learning with these related challenges

View All
JavaScript

Promise Time Limit

Wrap an async function so it gives up after a deadline — the building block behind every request timeout.

JavaScript · ES6Pratik Rai ·

JavaScript

Promise Pool

Run a list of async tasks with a hard limit on how many are in flight at once — the concurrency control Promise.all does not give you.

JavaScript · ES6Pratik Rai ·

JavaScript

Promisify a Callback Function

Convert a Node-style (error, value) callback API into one that returns a promise.

JavaScript · ES6Pratik Rai ·