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 OverviewOperationsset(1, 42, 1000)get(1)count()Cache StorageKey: 1, Value: 42Expires: currentTime + 1000Valid: ✓Resultsset → falseget → 42count → 1After TTL Expiresget(1) → -1 (expired), count() → 0Keys automatically become inaccessible after expiration
Understanding the Visualization
1
Input Operations
Set key 1 to value 42 with 1000ms TTL
2
Cache Storage
Store with current timestamp + duration as expiration
3
Access & Validation
Check if current time < expiration time on get/count
Key Takeaway
🎯 Key Insight: Store expiration timestamp with each entry and validate on every access for automatic TTL behavior
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