Batch Simulation of an Expiring LRU Key-Value Store
Data Structure DesignAuto-graded · 24 test casesLast updated
Replay a batch of timestamped get and set operations against a fixed-capacity store that combines per-key expiry with least-recently-used eviction.
Problem Statement
You are given a fixed-capacity key-value store, a list of operations to replay in order, and the arguments for each operation. Simulate the store and return the result of every get operation.
Each operation is either "set" or "get". The argument list at the same index holds that operation's arguments:
"set"takes[timestamp, key, value, ttl]. It storesvalueunderkeywith an expiration time oftimestamp + ttl."get"takes[timestamp, key]. It asks for the value currently stored underkey.
Rules for a live key. A key is live at time t when t < expires_at. At t == expires_at the key is already dead.
Rules for get(t, key):
- If
keyis not stored, the result is-1. - If
keyis stored butt >= expires_at, remove the key from the store and the result is-1. - Otherwise the result is the stored value. The key also becomes the most recently used entry.
Rules for set(t, key, value, ttl):
- If
keyis already stored (even if it has expired but has not yet been removed), overwrite its value and expiration with the new ones and make it the most recently used entry. This never causes an eviction. - If
keyis not stored and the store already holdscapacityentries, first evict the least recently used entry, then insert the new key as the most recently used entry. - Expired entries are not special during eviction. Eviction always removes the least recently used entry, whether or not it has expired. An expired entry keeps occupying a slot until a
getremoves it or eviction reaches it.
Output. Return a list with one element per operation, in order. For a "set" operation, the element is None. For a "get" operation, the element is the returned value (-1 when missing or expired).
Timestamps are non-decreasing across consecutive operations, so you can rely on that ordering.
Function Signature
Implement the function run_expiring_lru(capacity, ops, args) as described in the starter code. The parameters are:
capacity: the maximum number of entries the store can hold.ops: a list of"set"or"get"strings.args: a list whereargs[i]holds the argument list forops[i].
Constraints
1 <= capacity <= 10^51 <= len(ops) == len(args) <= 2 * 10^5- Each
ops[i]is either"set"or"get". 0 <= timestamp <= 10^91 <= ttl <= 10^61 <= len(key) <= 30, and keys are alphanumeric strings.0 <= value <= 10^9- For consecutive operations,
timestamp_i <= timestamp_{i+1}. - Each operation must run in O(1) average time. Scanning the whole store on every call is too slow.
Examples
Example 1
Input: run_expiring_lru(2, ['set', 'set', 'get', 'set', 'get', 'get', 'get'], [[1, 'a', 10, 5], [2, 'b', 20, 10], [3, 'a'], [4, 'c', 30, 5], [7, 'a'], [7, 'b'], [7, 'c']])
Output: [None, None, 10, None, -1, -1, 30]
Example 2
Input: run_expiring_lru(1, ['set', 'get', 'set', 'get'], [[0, 'k', 100, 10], [10, 'k'], [11, 'k', 200, 5], [12, 'k']])
Output: [None, -1, None, 200]
Example 3
Input: run_expiring_lru(2, ['set', 'set', 'get', 'get'], [[0, 'x', 1, 5], [1, 'y', 2, 5], [5, 'x'], [5, 'y']])
Output: [None, None, -1, 2]
Hints
Hint 1
Pair a hash map (key to value and expiry) with a recency order. Python's OrderedDict provides both hash lookup and O(1) move-to-end and pop-from-front.
Hint 2
Expiry is lazy. Check `t >= expires_at` only when a key is read with `get`. Never scan for expired keys.
Hint 3
In `set`, an existing key is an in-place update that never evicts. Only a brand-new key can trigger eviction, and that eviction always removes the least recently used entry.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Keep the store as an ordered map from key to (value, expires_at), where the front is the least recently used entry and the back is the most recently used one.
get: if the key is missing, return-1. Ift >= expires_at, delete the key and return-1. Otherwise move the key to the back and return its value.set: computeexpires_at = t + ttl. If the key already exists, overwrite its entry and move it to the back, with no eviction. If it is new and the store is full, remove the front entry first. Then insert the new key at the back.
Expiry is handled lazily. We never scan for dead entries. A dead entry is removed only when it is read or when it reaches the front during eviction. Eviction is purely by recency, as the rules require.
Why It Is Correct
- Recency order: the order changes only when a key is successfully read or written. The front is always the least recently used key, so evicting it follows the rules exactly.
- No stale reads: a value is returned only after the check
t < expires_atpasses. Expired entries that remain in the store are never returned. - Capacity: the store grows only on the branch for a new key. That branch evicts first when the store is full, so the size never exceeds
capacity. - Updates:
seton an existing key, expired or not, goes through the update branch. That branch does not evict and does not change the size.
Complexity
- Time: O(1) average per operation. This covers hash lookup,
move_to_end,popitem(last=False), and deletion. Total time is O(n) for n operations. - Space: O(min(capacity, number of distinct keys)) for the store.
Edge Cases
- Capacity 1: a new key always evicts the previous one. Updating the same key does not evict.
- Read exactly at expiry:
t == expires_atcounts as expired, so the key is removed and-1is returned. - Set on an expired but still stored key: it is an update, so the size is unchanged and nothing is evicted.
- Eviction of an expired entry: this is allowed. It is simply the least recently used entry.
- Reinsertion after removal: a key removed by
getor eviction is treated as new.
Implementation
from collections import OrderedDict
from typing import List, Optional
def run_expiring_lru(capacity: int, ops: List[str], args: List[List]) -> List[Optional[int]]:
store = OrderedDict() # key -> (value, expires_at); front = LRU, back = MRU
results: List[Optional[int]] = []
for op, params in zip(ops, args):
if op == "set":
timestamp, key, value, ttl = params
expires_at = timestamp + ttl
if key in store:
store[key] = (value, expires_at)
store.move_to_end(key)
else:
if len(store) >= capacity:
store.popitem(last=False)
store[key] = (value, expires_at)
results.append(None)
elif op == "get":
timestamp, key = params
entry = store.get(key)
if entry is None:
results.append(-1)
continue
value, expires_at = entry
if timestamp >= expires_at:
del store[key]
results.append(-1)
else:
store.move_to_end(key)
results.append(value)
else:
raise ValueError("Unknown operation")
return results