Skip to the solution
MediumDSA4 min read

Implement TimeLimitedCache (LeetCode 2622) with expiry

861 views

The problem

Problem, as an interviewer would state it: "Design a cache where set(key, value, duration) stores a value that expires after duration milliseconds. set returns true if an un-expired entry for that key already existed, otherwise false."

Examples:

Code
cache.set(1, 42, 100); // false (new key)
cache.set(1, 50, 50);  // true  (an unexpired entry existed; value and TTL overwritten)
cache.get(1);          // 50

Clarifying questions expected:

  • What should get return for a missing or expired key?
  • Does overwriting reset the expiry, and is it the NEW duration that applies?
  • Should there be a way to count the currently valid keys?

Code / implementation expected: Yes — real, direct proof of the expiry boundary, the overwrite return value, and cleanup, ideally testable without real waiting.

  • time-limited-cache
  • expiry
  • map

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

4 min read · 9 sections

Run the code

Edit the code and run it here. Each console line with an expected value becomes a test.

JavaScriptReal, direct proof: a TimeLimitedCache with an injectable clock behaves correctly at the expiry boundary, on overwrite, and when purging expired entries

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 98 of 154 in JavaScript coding

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

Up nextMedium

Implement Fisher-Yates Shuffle (in-place, unbiased)

Continue