Simulate a Time-To-Live (TTL) Key-Value Store
Data Structure DesignAuto-graded · 15 test casesLast updated
Process a series of operations on an in-memory key-value store with fixed time-to-live expiration dynamics.
Design and simulate a key-value store where each entry has a fixed duration (time-to-live or TTL) before it expires.
When the store is initialized, it is assigned a fixed positive integer ttl. The store processes a sequence of operations in order. Each operation is specified by an operation name and a list of arguments:
"put": Takes[key, value, now]. Inserts a new key-value pair or updates an existing one. The key's expiration timestamp is set tonow + ttl. ReturnsNone."get": Takes[key, now]. Returns thevalueassociated withkeyif the entry exists and has not expired at timestampnow. If the key does not exist or is expired, returnsNone. Note: an entry expires whenexpiry <= now(it remains strictly valid whileexpiry > now)."renew": Takes[key, now]. If the key exists and is not expired at timestampnow, updates its expiration timestamp tonow + ttl(retaining its current value) and returnsTrue. If the key is missing or expired, it cannot be renewed, and returnsFalse."count_live": Takes[now]. Returns the number of key-value pairs in the store that are still active/valid at timestampnow(i.e.,expiry > now).
Given ttl, a list of string operations, and a corresponding list of argument lists arguments, execute all operations sequentially and return a list containing the output of each operation.
Constraints
ttlis a positive integer.operationsandargumentshave equal length $N$ ($1 \le N \le 1000$).operations[i]is one of"put","get","renew", or"count_live".keyis a string.valuecan be any standard primitive data type (string, integer, etc.).nowis a non-negative integer.- An entry is valid strictly when
expiry > now. At the exact timestampnow = expiry, the entry is considered expired.
Examples
Example 1
Input: ttl_cache_operations(5, ['put', 'get', 'count_live', 'renew', 'get', 'count_live'], [['a', 1, 10], ['a', 14], [14], ['a', 14], ['a', 18], [19]])
Output: [None, 1, 1, True, 1, 0]
Example 2
Input: ttl_cache_operations(3, ['put', 'put', 'get', 'get', 'renew', 'count_live'], [['x', 'old', 1], ['x', 'new', 2], ['x', 4], ['x', 5], ['x', 5], [5]])
Output: [None, None, 'new', None, False, 0]
Worked solution
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Approach
We can maintain the state of the cache using a dictionary (hash map) where the key is the entry key and the value is a tuple containing (value, expiry_timestamp).
For each operation in the input sequence, we apply the logic according to the timestamp now:
"put": We update or addkeyin the map set to(value, now + ttl)and appendNoneto the output list."get": We look upkey. If present andexpiry > now, we append itsvalue. Otherwise (missing orexpiry <= now), we appendNone."renew": We look upkey. If present andexpiry > now, we update its entry to(value, now + ttl)and appendTrue. Otherwise, we appendFalse."count_live": We iterate over all stored entries and count how many haveexpiry > now, then append the count to the output list.
Complexity
- Time Complexity:
"put","get","renew"run in $O(1)$ average time per operation using hash map lookups."count_live"runs in $O(K)$ time where $K$ is the number of distinct keys currently stored in the map.- Overall time complexity for $N$ operations is $O(N \cdot K)$ in the worst case if
"count_live"is called frequently. Given $N \le 1000$, this readily runs well within time limits.
- Space Complexity: $O(K)$ space to store up to $K$ distinct keys in memory.
Python 3 Reference Solution
from typing import List, Dict, Tuple, Any
def ttl_cache_operations(ttl: int, operations: List[str], arguments: List[List[object]]) -> List[object]:
cache: Dict[str, Tuple[Any, int]] = {}
results = []
for op, args in zip(operations, arguments):
if op == "put":
key, val, now = args[0], args[1], args[2]
cache[key] = (val, now + ttl)
results.append(None)
elif op == "get":
key, now = args[0], args[1]
if key in cache:
val, expiry = cache[key]
if expiry > now:
results.append(val)
else:
results.append(None)
else:
results.append(None)
elif op == "renew":
key, now = args[0], args[1]
if key in cache:
val, expiry = cache[key]
if expiry > now:
cache[key] = (val, now + ttl)
results.append(True)
else:
results.append(False)
else:
results.append(False)
elif op == "count_live":
now = args[0]
count = sum(1 for _, expiry in cache.values() if expiry > now)
results.append(count)
return results