Simulate a Fixed-Size Cache Under LRU or LFU Eviction
Data Structure DesignAuto-graded · 18 test casesLast updated
Replay a list of get/put operations on a bounded cache that evicts by recency or by frequency (ties broken by recency), and return the result of each operation.
Simulate a Bounded Cache
A cache holds at most capacity integer key/value pairs. When a new key arrives and the cache is already full, one existing entry must be removed first. Which entry goes depends on the policy, which is either "LRU" or "LFU".
You are given a policy name and a list of operations to run in order. Return what each operation produces.
Operations
Operation i is operations[i] with its parameters in arguments[i].
"get"witharguments[i] = [key]: if the key is stored, return its value and count the lookup as a use of that key. If the key is absent, return-1and change nothing."put"witharguments[i] = [key, value]: store the value under the key and returnNone.- If the key is already stored, overwrite its value. This counts as a use of the key. Nothing is evicted.
- If the key is new and the cache is full, evict one entry first, then insert the new key. The new key counts as having been used once, and it is the most recently used key.
- If the key is new and the cache has room, simply insert it with the same starting state.
Eviction rules
- LRU (least recently used): evict the key whose most recent use is the oldest. Insertions, successful
getcalls, and overwritingputcalls all count as uses. - LFU (least frequently used): each key has a use count. It starts at 1 on insertion and goes up by 1 for every successful
getand every overwritingput. Evict the key with the smallest count. If several keys share that smallest count, evict the one among them whose most recent use is the oldest. A key that is evicted loses its count; if it is inserted again later it starts over at 1.
Always evict before inserting, so the incoming key can never be the one removed.
Output
Return a list with one entry per operation, in the same order: the retrieved value (or -1) for each get, and None for each put.
Constraints
capacityis a positive integer.policyis either"LRU"or"LFU".operationsandargumentshave the same length, and every operation is"get"or"put".- Keys and values are integers.
- A
geton a key that is not currently stored returns-1and does not affect any usage information. - An efficient solution should handle each operation in O(1) average time.
Examples
Example 1
Input: simulate_cache(2, 'LRU', ['put', 'put', 'get', 'put', 'get'], [[1, 1], [2, 2], [1], [3, 3], [2]])
Output: [None, None, 1, None, -1]
Example 2
Input: simulate_cache(2, 'LFU', ['put', 'put', 'get', 'put', 'get'], [[1, 1], [2, 2], [1], [3, 3], [2]])
Output: [None, None, 1, None, -1]
Hints
Hint 1
Keep the values in an ordinary dictionary. Only the choice of eviction victim depends on the policy, so track that separately.
Hint 2
For LRU, an OrderedDict lets you move a key to the end on every use and pop the oldest key from the front, both in constant time.
Hint 3
For LFU, group keys into buckets by use count, with each bucket ordered by recency, and track the smallest count that has a non-empty bucket. Reset that minimum to 1 whenever a brand new key is inserted, and remember to evict before inserting.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Keep the actual data in a plain dictionary, key -> value. The only policy-specific part is deciding which key to evict, so each policy gets its own bookkeeping structure. Every step is a constant-time hash or ordered-dict operation.
LRU
Use an OrderedDict whose order runs from least recently used (front) to most recently used (back).
- Successful
getor overwritingput:move_to_end(key). - New key: append it at the back. If the cache is full, first
popitem(last=False)to remove the front key, and delete it from the value dictionary.
LFU
Maintain three things:
count[key]: the current use count.buckets[c]: anOrderedDictof the keys with countc, oldest use first.lowest: the smallest count that has a non-empty bucket.
On a use, move the key from bucket c to bucket c + 1 (appending it, so it is the newest in that bucket). If bucket c became empty and c == lowest, increase lowest to c + 1; that bucket is guaranteed to contain the key we just moved.
On inserting a new key into a full cache, pop the oldest key from buckets[lowest]. That is the smallest count, with ties broken by least recent use. Delete its value and count, then insert the new key in bucket 1 and set lowest = 1.
Why it is correct
- LRU: the ordered dictionary is always sorted by last use, because every use moves the key to the back. The front is therefore the least recently used key.
- LFU: each key lives in exactly one bucket matching its count, and within a bucket keys are ordered by last use.
lowestonly grows through a use, in which case the destination bucket is non-empty, and it resets to 1 on every new insertion. After an evictionlowestmay point at an emptied bucket, but an insertion always follows immediately and resets it. - Evicting before inserting prevents the new key (count 1) from being chosen as its own victim.
- An overwriting
putnever evicts and counts as a use, matching the rules in the statement. - A
geton a missing key returns-1and touches no state.
Complexity
- Time: O(1) average per operation, so O(n) for n operations.
- Space: O(capacity) for the value store, order tracking, counts and buckets.
Reference solution
from collections import OrderedDict, defaultdict
from typing import List, Optional
def simulate_cache(capacity: int, policy: str, operations: List[str], arguments: List[List[int]]) -> List[Optional[int]]:
store = {}
results = []
if policy == "LRU":
recency = OrderedDict()
for op, args in zip(operations, arguments):
if op == "get":
key = args[0]
if key not in store:
results.append(-1)
else:
recency.move_to_end(key)
results.append(store[key])
else:
key, value = args
if key in store:
store[key] = value
recency.move_to_end(key)
else:
if len(store) == capacity:
victim, _ = recency.popitem(last=False)
del store[victim]
store[key] = value
recency[key] = None
results.append(None)
return results
count = {}
buckets = defaultdict(OrderedDict)
lowest = 0
def bump(key):
nonlocal lowest
c = count[key]
del buckets[c][key]
if not buckets[c] and lowest == c:
lowest = c + 1
count[key] = c + 1
buckets[c + 1][key] = None
for op, args in zip(operations, arguments):
if op == "get":
key = args[0]
if key not in store:
results.append(-1)
continue
bump(key)
results.append(store[key])
else:
key, value = args
if key in store:
store[key] = value
bump(key)
else:
if len(store) == capacity:
victim, _ = buckets[lowest].popitem(last=False)
del store[victim]
del count[victim]
store[key] = value
count[key] = 1
buckets[1][key] = None
lowest = 1
results.append(None)
return results