Cache with Expiry - Problem

Design and implement a Cache with Expiry that stores key-value pairs with a time-to-live (TTL) mechanism.

Your cache should support the following operations:

  • put(key, value, ttl) - Store a key-value pair that expires after ttl seconds
  • get(key) - Retrieve the value for a key if it hasn't expired, otherwise return null
  • delete(key) - Remove a key from the cache
  • size() - Return the number of non-expired keys currently in the cache

Keys expire based on the TTL (time-to-live) value provided when they were stored. Once a key expires, it should be treated as if it doesn't exist in the cache.

Input & Output

Example 1 — Basic Cache Operations
$ Input: operations = [["put","key1","value1",5], ["get","key1"], ["size"], ["get","key1"], ["size"]]
Output: [null, "value1", 1, null, 0]
💡 Note: Put key1 with 5-second TTL, get immediately returns value1, size is 1. After 5+ seconds, key1 expires so get returns null and size becomes 0.
Example 2 — Multiple Keys with Different TTLs
$ Input: operations = [["put","a","apple",3], ["put","b","banana",10], ["get","a"], ["get","b"], ["size"]]
Output: [null, null, "apple", "banana", 2]
💡 Note: Store 'a' for 3 seconds and 'b' for 10 seconds. Both are accessible initially, and cache size is 2.
Example 3 — Delete Operation
$ Input: operations = [["put","x","test",60], ["delete","x"], ["get","x"], ["delete","x"]]
Output: [null, true, null, false]
💡 Note: Put 'x' with 60-second TTL. Delete returns true (key existed). Get returns null (key was deleted). Second delete returns false (key doesn't exist).

Constraints

  • 1 ≤ operations.length ≤ 1000
  • operations[i] is one of ["put", "get", "delete", "size"]
  • 1 ≤ key.length, value.length ≤ 100
  • 1 ≤ ttl ≤ 109 seconds

Visualization

Tap to expand
INPUTALGORITHM STEPSRESULTput('key1', 'val1', 10)Store for 10 secondsget('key1')size()get('key1') after 11sKey should be expired1Hash Map StorageStore key → (value, expiry_time)2Lazy Expiry CheckCheck timestamp only on access3O(1) OperationsDirect hash map lookup4Automatic CleanupRemove expired on accessCache stores entrykey1 → ('val1', t+10s)Returns: 'val1'Returns: 1Returns: nullKey expired, removedKey Insight:Store expiration timestamps with values and use lazy validation for O(1) cache operations.Only check expiry when accessing specific keys, avoiding expensive full-cache scans.TutorialsPoint - Cache with Expiry | Lazy Expiry Check
Asked in
Amazon 45 Google 38 Microsoft 32 Facebook 28
34.2K Views
High Frequency
~25 min Avg. Time
890 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