Skip to solution
mediumDSA

Implement TimeLimitedCache (LeetCode 2622) with expiry

861 views
01

Understand the problem

Design a cache where set(key, value, duration) stores value that expires after duration ms. Return true if un-expired key existed.

time-limited-cacheexpirymap
02

Attempt it yourself

Sketch your approach before reading the solution — that's what interviews test.

Nudge consolestandby

Stuck? Beam a request up — the console returns a conceptual nudge that guides your logic without spoiling the implementation.

03

Study the solution

Approach: Map stores {value, timer}. On set, clear old timer if exists, set new setTimeout to delete.

class TimeLimitedCache {
  constructor() { this.map = new Map(); }
  set(key, value, duration) {
    const exists = this.map.has(key);
    if (exists) clearTimeout(this.map.get(key).timer);
   

Solution ready — 2 min read

Classified // press E to declassify

04

Join the discussion

Discussion (0)

Sign in to join the discussion.

No responses yet. Be the first to share what you think.

Transmission complete // awaiting log

KEEP THE
STREAK ALIVE.

Dossier 122 of 190 decoded in the JavaScript Coding track. One more won't hurt.

Back to track