Cache With Time Limit - Problem

Design a time-based cache class that allows getting and setting key-value pairs with expiration times.

The class should have three public methods:

  • set(key, value, duration): Accepts an integer key, integer value, and duration in milliseconds. Returns true if the same unexpired key already exists, false otherwise. Overwrites both value and duration if key exists.
  • get(key): Returns the associated value if an unexpired key exists, otherwise returns -1.
  • count(): Returns the count of unexpired keys.

Keys automatically become inaccessible once their duration has elapsed.

Input & Output

Example 1 — Basic Cache Operations
$ Input: operations = [["set", 1, 42, 1000], ["get", 1], ["count"], ["get", 1]]
Output: [false, 42, 1, 42]
💡 Note: Set key 1 to 42 with 1000ms TTL (returns false - no existing key). Get key 1 returns 42. Count returns 1 active key. Get key 1 again still returns 42.
Example 2 — Key Overwrite
$ Input: operations = [["set", 1, 10, 1000], ["set", 1, 20, 2000], ["get", 1]]
Output: [false, true, 20]
💡 Note: First set returns false (no existing key). Second set returns true (key 1 exists and is valid). Get returns new value 20.
Example 3 — Expiration Test
$ Input: operations = [["set", 1, 100, 50], ["count"], ["count"]]
Output: [false, 1, 0]
💡 Note: Set key 1 with 50ms TTL. First count returns 1. After 50ms delay, second count returns 0 (expired).

Constraints

  • 1 ≤ operations.length ≤ 100
  • 0 ≤ key ≤ 105
  • 1 ≤ value ≤ 108
  • 1 ≤ duration ≤ 1000

Visualization

Tap to expand
Cache With Time Limit INPUT Operations: set(1, 42, 1000) key=1, val=42, dur=1000ms get(1) count() get(1) Cache Structure: Map<key, {value, expiry}> key: 1 val:42, exp:T+1000 Background Timer ALGORITHM STEPS 1 set(1, 42, 1000) Store key with expiry time expiry = now + 1000ms --> false 2 get(1) Check if key exists & valid now < expiry? Return val --> 42 3 count() Count unexpired keys Filter valid entries --> 1 4 get(1) again Still within duration Return cached value --> 42 Lazy Cleanup: Only check expiry when accessing keys FINAL RESULT Output Array: false 42 1 42 [0] [1] [2] [3] Result Breakdown: false: Key 1 was new 42: Value for key 1 1: One active key 42: Key 1 still valid OK - All operations valid! Timeline (within 1000ms): set get count get Key Insight: Lazy Cleanup stores entries with expiry timestamps. Instead of actively removing expired keys, we check validity on access (get/count). Background timer can optionally clean up periodically. Time Complexity: O(1) for set/get, O(n) for count | Space Complexity: O(n) TutorialsPoint - Cache With Time Limit | Lazy Cleanup with Background Timer
Asked in
Google 35 Amazon 28 Microsoft 22 Facebook 18
23.4K Views
Medium Frequency
~25 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen