Replay a Log on a Budgeted Recency Cache
Data Structure DesignAuto-graded · 18 test casesLast updated
Simulate a least-recently-used cache whose budget is the sum of per-entry sizes, replaying an operation log and returning each result, using hashing plus recency ordering.
Budgeted Recency Cache Simulator
A cache stores entries, each identified by an integer key and carrying an integer value and a positive integer size. Unlike a normal LRU cache, which limits how many entries it holds, this cache limits the sum of the sizes of all entries it holds. An entry of size 3 uses 3 units of the budget.
You are given a log of operations to replay, in order, on one such cache. Return the result of every operation.
Operations
Each operation is a string, paired with a list of integer arguments at the same position in arguments:
"WeightedLRUCache"with[budget]: creates a new, empty cache whose total size may never exceedbudget. Any previous contents are discarded. The result isNone."get"with[key]: if the key is stored, the result is its value and the key becomes the most recently used. If it is not stored, the result is-1and nothing changes, including recency."put"with[key, value, size]: the result isNone. It works as follows:- If the key is already stored, replace its value and size with the new ones. Otherwise, add it as a new entry.
- In both cases, the key becomes the most recently used.
- Then, while the total size of all stored entries is greater than the budget, remove the least recently used entry.
A removed key is completely gone. A later get on it gives -1, and a later put adds it as a brand-new entry.
Task
Implement weighted_lru_cache(operations, arguments), which processes the log in order and returns a list with one result per operation: None for "WeightedLRUCache" and "put", and the retrieved value or -1 for "get".
Because the key being written is made most recently used before any removal happens, it is always the last candidate for removal.
Constraints
1 <= budget <= 10^91 <= size <= budgetfor everyput0 <= key, value <= 10^9operationsandargumentshave the same length.- At most
2 * 10^5getandputoperations in total. - The first operation is always
"WeightedLRUCache". - Aim for amortized
O(1)time per operation.
Examples
Example 1
Input: weighted_lru_cache(['WeightedLRUCache', 'put', 'put', 'get', 'put', 'get', 'get'], [[5], [1, 10, 2], [2, 20, 2], [1], [3, 30, 3], [2], [1]])
Output: [None, None, None, 10, None, -1, 10]
Example 2
Input: weighted_lru_cache(['WeightedLRUCache', 'put', 'put', 'get', 'put', 'get', 'get'], [[3], [1, 100, 1], [2, 200, 2], [1], [3, 300, 1], [2], [3]])
Output: [None, None, None, 100, None, -1, 300]
Hints
Hint 1
You need O(1) lookup by key and O(1) removal of an arbitrary entry plus O(1) removal of the oldest entry. Think about a hash map combined with a recency-ordered list, or Python's OrderedDict.
Hint 2
Keep a running total of sizes instead of recomputing it. When overwriting an existing key, subtract its old size before adding the new one.
Hint 3
Move the written key to the most-recent end before running the eviction loop, and use a while loop since one large put may evict several entries. Since size <= budget, the loop never removes the key just written.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
We need three things to be fast: find an entry by key, move an entry to the "most recent" end, and remove the "least recent" entry. A hash map combined with a doubly linked list gives all three in O(1). Python's OrderedDict is exactly that combination, so we use it with the front as least recent and the back as most recent.
Each entry stores (value, size). We also keep an integer total holding the sum of sizes currently stored. We never recompute it; we adjust it on every insert, overwrite and removal.
- Constructor entry: record the budget, clear the cache, reset
totalto 0, and outputNone. get: if the key is missing, output-1without touching anything. Otherwise pop the entry and re-insert it, which moves it to the most-recent end, and output its value.put:- If the key exists, pop it and subtract its old size from
total. - Insert the new
(value, size)at the most-recent end and add the new size tototal. - While
total > budget, pop the least-recent entry and subtract its size. - Output
None.
- If the key exists, pop it and subtract its old size from
Why it is correct
- Every successful access (a
gethit, aputoverwrite, aputinsert) moves the key to the back. Other keys keep their relative order, so the front is always the least recently used key, which is what must be evicted first. - Subtracting the old size before adding the new one keeps
totalequal to the true sum. Otherwise shrinking an entry would leave an inflated total and cause wrong evictions. - The written key is already at the back when eviction starts. If everything else were removed, the total would equal
size <= budget, so the loop would have stopped. Hence the loop never empties the cache and the written key survives. - A missed
getchanges nothing, matching the rule that recency is only affected by hits.
Complexity
- Time: each operation is O(1) on average aside from evictions. Every entry added can be evicted at most once, so total eviction work is bounded by the number of
putcalls. Overall O(n) for n operations. - Space: O(k) for the k entries stored at once, plus O(n) for the output list. Nothing is proportional to the budget or sizes, which can reach 10^9.
Reference solution
from collections import OrderedDict
from typing import List, Optional
def weighted_lru_cache(operations: List[str], arguments: List[List[int]]) -> List[Optional[int]]:
cache = OrderedDict() # key -> (value, size); front = least recent, back = most recent
total = 0
budget = 0
result = []
for op, args in zip(operations, arguments):
if op == "WeightedLRUCache":
budget = args[0]
cache.clear()
total = 0
result.append(None)
elif op == "get":
key = args[0]
if key not in cache:
result.append(-1)
else:
entry = cache.pop(key)
cache[key] = entry
result.append(entry[0])
elif op == "put":
key, value, size = args
if key in cache:
_, old_size = cache.pop(key)
total -= old_size
cache[key] = (value, size)
total += size
while total > budget:
_, (_, removed_size) = cache.popitem(last=False)
total -= removed_size
result.append(None)
return result