Build a Time-Aware Key-Value Store with Expiration Logic
Data Structure DesignAuto-graded · 23 test casesLast updated
Tests data structure design, time-based expiration semantics, and clean handling of missing or stale entries in an in-memory cache.
You are building an in-memory key-value store that supports automatic expiration of entries. Your store must handle write, read, and removal operations, along with the ability to simulate the passage of time for testing purposes.
Implement a function that processes a sequence of operations on the store and returns the result of each operation.
Operations
Your function receives two parallel lists: operations (operation names) and arguments (parameters for each operation). Process them in order and return a list of results.
Supported operations:
-
"set"with arguments[key, value]or[key, value, ttl]: Store the value under the given key. Ifttl(time-to-live, in seconds) is provided, the entry expires after that duration from the current simulated time. Ifttlis omitted, the entry never expires. Overwrites any existing entry for that key. ReturnsNone. -
"get"with arguments[key]: Retrieve the value stored under the key. If the key does not exist or has expired, returnNone. Expired entries should be removed when accessed. -
"delete"with arguments[key]: Remove the entry for the key. ReturnsTrueif a non-expired entry was removed,Falseif the key did not exist or had already expired. -
"advance_time"with arguments[seconds]: Move the simulated clock forward by the given number of seconds. ReturnsNone.
Expiration Rules
- Time starts at 0.0 seconds.
- An entry set with
ttl=Texpires at timecurrent_time + T. - An entry is considered expired if the current time is greater than or equal to its expiration timestamp.
- Overwriting a key replaces both its value and expiration time.
- Keys without a
ttlnever expire unless deleted or overwritten.
Constraints
- 1 ≤ number of operations ≤ 1000
- Keys are non-empty strings
- Values can be any Python object (integers, strings, lists, dictionaries, etc.)
ttlwhen provided is a positive number (int or float)secondsinadvance_timeis non-negative- All operations are valid (no unknown operation names)
Examples
Example 1
Input: run_cache_operations(['set', 'get', 'advance_time', 'get', 'delete', 'get'], [['a', 1, 5], ['a'], [5], ['a'], ['a'], ['a']])
Output: [None, 1, None, None, False, None]
Example 2
Input: run_cache_operations(['set', 'advance_time', 'set', 'advance_time', 'get'], [['x', 'old', 10], [4], ['x', 'new', 3], [3], ['x']])
Output: [None, None, None, None, None]
Example 3
Input: run_cache_operations(['get', 'delete', 'set', 'delete'], [['missing'], ['missing'], ['k', {'v': [1, 2]}], ['k']])
Output: [None, False, None, True]
Hints
Hint 1
Store each entry as a tuple containing both the value and its expiration timestamp (or None if it never expires).
Hint 2
When retrieving a key, check if it has expired by comparing the current simulated time against the stored expiration timestamp.
Hint 3
Use lazy deletion: remove expired entries when they are accessed rather than scanning the entire store periodically.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The core idea is to maintain a hash table that maps each key to a pair: the stored value and an expiration timestamp. We track a simulated clock that starts at zero and advances only when explicitly instructed.
Data structure choice: A dictionary provides O(1) average-case lookup, insertion, and deletion. Each entry stores (value, expiration_time) where expiration_time is None for entries that never expire, or a timestamp for those that do.
Expiration handling: We use lazy deletion—expired entries remain in the store until accessed. When a get or delete operation encounters a key, we check if current_time >= expiration_time. If expired, we remove the entry and treat it as non-existent. This avoids the overhead of background cleanup threads or periodic scans.
Operation details:
- set: Store or overwrite the entry. Calculate expiration as
current_time + ttlif ttl is provided. - get: Check existence and expiration. Return the value if valid,
Noneotherwise. - delete: Check if the key exists and is not expired. Return
Trueonly if we deleted a valid entry. - advance_time: Increment the simulated clock. Expired entries are cleaned up lazily on subsequent access.
Correctness: The approach correctly handles overwriting (which resets expiration), distinguishes between missing and expired keys, and ensures expired entries are invisible without requiring real-time delays in tests.
Complexity
- Time: O(1) per operation on average (hash table operations)
- Space: O(n) where n is the number of stored keys
Solution
from typing import List
def run_cache_operations(operations: List[str], arguments: List[List]) -> List:
store = {} # key -> (value, expiration_timestamp or None)
current_time = 0.0
output = []
for op, args in zip(operations, arguments):
if op == "set":
key, value = args[0], args[1]
ttl = args[2] if len(args) > 2 else None
expiration = None if ttl is None else current_time + ttl
store[key] = (value, expiration)
output.append(None)
elif op == "get":
key = args[0]
if key not in store:
output.append(None)
else:
value, expiration = store[key]
if expiration is not None and current_time >= expiration:
del store[key]
output.append(None)
else:
output.append(value)
elif op == "delete":
key = args[0]
if key in store:
value, expiration = store[key]
if expiration is None or current_time < expiration:
del store[key]
output.append(True)
else:
del store[key]
output.append(False)
else:
output.append(False)
elif op == "advance_time":
current_time += args[0]
output.append(None)
return output