Simulate an Expiring Key-Value Store with Read-Through Loads
Data Structure DesignAuto-graded · 22 test casesLast updated
Simulate a time-aware key-value store with expiry, stale entries that stay stored, and a read-through fetch whose loader outcome is given as data, with strict input validation.
Simulate an Expiring Key-Value Store with Read-Through Loads
You are given a list of commands to run, in order, against an initially empty key-value store whose entries can expire. Write a function that returns one result list per command.
Commands
Each command is a list. The first element is the command name and the second is the timestamp time_ms.
| Command | Format |
|---|---|
| put | ["put", time_ms, key, value, ttl_ms] |
| get | ["get", time_ms, key] |
| delete | ["delete", time_ms, key] |
| size | ["size", time_ms] |
| fetch | ["fetch", time_ms, key, ttl_ms, loader_status, loader_payload] |
Keys are strings. Stored values are integers. Timestamps are nonnegative integers and must never decrease from one command to the next (equal timestamps are allowed).
Expiry rules
- If
ttl_ms > 0, an entry written at timetexpires att + ttl_ms. It is usable only while the current time is strictly less than that expiry, so at exactlyt + ttl_msit is already unusable. - If
ttl_ms == 0, the entry never expires. - An expired entry is not removed automatically. It stays stored until it is removed by
deleteor overwritten byputor a successfulfetch. Onlydeleteand overwriting remove it.get,size, andfetchnever remove anything.
Call an entry valid at time t if its key is stored and it has not expired at t.
Results
- put: store
valueunderkeywith the given TTL, replacing any existing entry (including its expiry), and return["ok"]. - get: return
["ok", value]if the key holds a valid entry, otherwise["ok", null]. - delete: remove the key if it is stored, and return
["ok", true]if it was stored (even if expired) or["ok", false]if it was not stored. - size: return
["ok", count], wherecountis the number of stored keys, including expired ones. - fetch: the loader is not a function. Its outcome is supplied as data in
loader_statusandloader_payload.- If the key holds a valid entry, return
["ok", cached_value]and do not look at the loader fields. - Otherwise (key missing or expired), look at
loader_status:"ok":loader_payloadis an integer. Store it underkey, replacing any existing entry, with expiry computed from the current time andttl_msusing the same rules asput. Return["ok", loader_payload]."error":loader_payloadis a string reason. Leave the store completely unchanged (an expired entry stays stored) and return["error", reason].
- If the key holds a valid entry, return
Invalid input
Raise ValueError if any of the following occurs:
- The command list is not a list, or a command is not a non-empty list.
- The command name is not a string or is not one of the five names above.
- A command has the wrong number of elements for its name.
- A timestamp is not an integer, is negative, or is smaller than the previous command's timestamp.
- A key is not a string.
- A
putvalue or TTL, or afetchTTL, is not an integer, or a TTL is negative. - On a
fetchthat does not hit a valid entry:loader_statusis neither"ok"nor"error", an"ok"payload is not an integer, or an"error"payload is not a string.
Booleans are not accepted as integers. On a fetch that hits a valid entry, the loader fields are not examined.
Constraints
0 <= len(commands) <= 200000- Timestamps are nonnegative integers in nondecreasing order.
- TTL values are nonnegative integers.
- Values and
"ok"payloads are integers. Keys and error reasons are strings. - Results are compared exactly.
Examples
Example 1
Input: run_expiring_store([['put', 0, 'u', 1, 5], ['get', 4, 'u'], ['get', 5, 'u'], ['size', 5], ['fetch', 6, 'u', 10, 'ok', 2], ['fetch', 7, 'v', 0, 'error', 'db_down'], ['size', 7], ['delete', 8, 'u'], ['size', 8]])
Output: [['ok'], ['ok', 1], ['ok', None], ['ok', 1], ['ok', 2], ['error', 'db_down'], ['ok', 1], ['ok', True], ['ok', 0]]
Hints
Hint 1
Separate two ideas: a key being stored (what size and delete care about) and a stored entry being valid right now (what get and fetch care about).
Hint 2
A fetch has two stages: first check for a valid entry and return it immediately; only if that fails, act on the supplied loader status.
Hint 3
Represent no-expiry as a sentinel such as None, and treat an entry as valid when the sentinel is present or the current time is strictly less than the expiry. Remember that Python's bool is a subclass of int, so check the type exactly.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Keep a dictionary mapping each key to a pair (value, expires_at), where expires_at is None for entries that never expire. The key idea is to keep two questions apart:
- Is the key stored? Only
sizeanddeletecare about this. - Is the entry valid at the current time? This holds when
expires_at is Noneornow < expires_at. Onlygetand the check step offetchcare about this.
Because expired entries are removed only by delete or by being overwritten, no background cleanup or lazy eviction is needed. One dictionary and one validity check are enough.
Each command is handled as follows:
- put: write a fresh pair, which replaces any old value and old expiry together.
- get: return the value if the entry exists and is valid, otherwise
None. - delete: report whether the key was stored (regardless of validity), then remove it.
- size: return the number of stored keys, expired ones included.
- fetch: first check for a valid entry and return it, ignoring the loader fields. Otherwise act on the loader status. For
"ok", store the payload with a freshly computed expiry and return it. For"error", change nothing and return the reason.
Before executing each command, validate it: the name and arity, an integer nonnegative timestamp that does not decrease, a string key, and integer or string payloads of the right kind. Check types with type(x) is int so that booleans are rejected.
Why it is correct
- A positive TTL gives
expires_at = t + ttl, and validity requiresnow < expires_at, so the entry is invalid at exactly the expiry instant. - TTL zero maps to
None, so the entry never expires. - Every write replaces the whole tuple, so an old expiry can never carry over into a new entry.
- A failed fetch does not touch the dictionary, so an expired entry remains stored and is still counted by
sizeand reported bydelete. - The state after each command depends only on the dictionary and the current command, so processing in order gives the specified results.
Complexity
- Time: O(1) average per command, so O(n) for n commands.
- Space: O(k) for k distinct stored keys, plus O(n) for the results.
Reference solution
from typing import List
def run_expiring_store(commands: List[List[object]]) -> List[List[object]]:
if not isinstance(commands, list):
raise ValueError("commands must be a list")
arity = {"put": 5, "get": 3, "delete": 3, "size": 2, "fetch": 6}
store = {} # key -> (value, expires_at or None)
results = []
last_time = -1
def is_valid(entry, now):
expires_at = entry[1]
return expires_at is None or now < expires_at
def expiry(now, ttl):
return None if ttl == 0 else now + ttl
for cmd in commands:
if not isinstance(cmd, list) or not cmd or not isinstance(cmd[0], str):
raise ValueError("malformed command")
name = cmd[0]
if name not in arity or len(cmd) != arity[name]:
raise ValueError("unknown command or wrong arity")
now = cmd[1]
if type(now) is not int or now < 0 or now < last_time:
raise ValueError("invalid timestamp")
last_time = now
if name == "size":
results.append(["ok", len(store)])
continue
key = cmd[2]
if not isinstance(key, str):
raise ValueError("key must be a string")
if name == "put":
value, ttl = cmd[3], cmd[4]
if type(value) is not int or type(ttl) is not int or ttl < 0:
raise ValueError("invalid value or ttl")
store[key] = (value, expiry(now, ttl))
results.append(["ok"])
elif name == "get":
entry = store.get(key)
if entry is not None and is_valid(entry, now):
results.append(["ok", entry[0]])
else:
results.append(["ok", None])
elif name == "delete":
existed = key in store
store.pop(key, None)
results.append(["ok", existed])
else: # fetch
ttl, status, payload = cmd[3], cmd[4], cmd[5]
if type(ttl) is not int or ttl < 0:
raise ValueError("invalid ttl")
entry = store.get(key)
if entry is not None and is_valid(entry, now):
results.append(["ok", entry[0]])
continue
if status == "ok":
if type(payload) is not int:
raise ValueError("ok payload must be an integer")
store[key] = (payload, expiry(now, ttl))
results.append(["ok", payload])
elif status == "error":
if not isinstance(payload, str):
raise ValueError("error payload must be a string")
results.append(["error", payload])
else:
raise ValueError("invalid loader status")
return results