Process LFU Cache Operations with Frequency and Recency Eviction
Data Structure DesignAuto-graded · 22 test casesLast updated
Simulate a Least Frequently Used (LFU) cache supporting fast O(1) operations, breaking tie frequencies by least recent usage.
Design and execute a simulation of a Least Frequently Used (LFU) cache of fixed size capacity.
The cache stores integer keys mapped to integer values, along with a use count for each resident key. When inserting a new key into a full cache, the cache must remove the key with the strictly smallest use count. If multiple keys tie for the minimum use count, the key that was least recently used among them is evicted.
You will be given the maximum size capacity, a list of string commands ops, and a matching list of argument lists args. Process the sequence of operations in order and return a list containing the output of all get operations.
Operations Behavior
get(key)(represented byops[i] = "get"andargs[i] = [key]):- If
keyis present in the cache, increment its use count, update its recency to be the most recent, and record its stored value in the output. - If
keyis not present, record-1in the output. Count remains unchanged.
- If
put(key, value)(represented byops[i] = "put"andargs[i] = [key, value]):- If
keyis already present: overwrite its value withvalue, increment its use count, and update its recency to be the most recent. No eviction occurs. - If
keyis not present:- If the total number of cached keys has reached
capacity, evict the key with the minimum use count (breaking ties by evicting the least recently accessed key among those with minimum count). - Store the new
(key, value)pair with an initial use count of 1. Mark this key as the most recently used.
- If the total number of cached keys has reached
putoperations do not produce an output entry.
- If
An evicted key completely forfeits its prior access history. If re-inserted later, its use count resets to 1.
Constraints
1 <= capacity <= 10^41 <= len(ops) == len(args) <= 2 * 10^50 <= key <= 10^50 <= value <= 10^9- Each operation should execute in average $O(1)$ time complexity.
Examples
Example 1
Input: simulate_lfu_cache(2, ['put', 'put', 'get', 'put', 'get', 'get', 'put', 'get', 'get', 'get'], [[1, 10], [2, 20], [1], [3, 30], [2], [3], [4, 40], [1], [3], [4]])
Output: [10, -1, 30, -1, 30, 40]
Example 2
Input: simulate_lfu_cache(1, ['put', 'put', 'get', 'put', 'get', 'get'], [[5, 1], [5, 2], [5], [6, 3], [5], [6]])
Output: [2, -1, 3]
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Method Explanation
An efficient Least Frequently Used (LFU) cache design requires two primary capabilities in $O(1)$ time:
- Fast lookup and updating of a key's value and frequency.
- Instant retrieval of the key with the minimum frequency, breaking ties by least recency.
We can achieve average $O(1)$ performance per operation using a hash map combined with frequency buckets:
val_map: Mapskey -> value.freq_map: Mapskey -> frequency.buckets: Mapsfrequency -> OrderedDict of keys. In Python,OrderedDictmaintains insertion order. The front of theOrderedDictis the least recently used key for that frequency bucket, while the back is the most recently used.min_freq: An integer tracking the current minimum frequency of any key present in the cache.
Maintenance Rules:
- Access / Update (
touch): When an existing key is accessed or updated, its count increases from $f$ to $f + 1$. We remove the key frombuckets[f]and insert it at the end ofbuckets[f + 1]. Ifbuckets[f]becomes empty andmin_freq == f, thenmin_freqincrements to $f + 1$. - Insertion of New Key: If the cache is full, we evict the key at the front of
buckets[min_freq]using.popitem(last=False). Afterwards, we insert the new key intobuckets[1]and explicitly setmin_freq = 1.
Because a fresh insertion always resets min_freq = 1, and a count increment can only increase min_freq by 1 when its previous bucket empties out, we never need to search linearly for the minimum frequency.
Complexity Analysis
- Time Complexity: $O(1)$ average time per operation. Hash map lookups and
OrderedDictadditions/deletions take $O(1)$ average time. Over $N$ operations, total processing time is $O(N)$. - Space Complexity: $O(\text{capacity})$ to store the cached elements and frequency buckets.
Python 3 Implementation
from typing import List
from collections import defaultdict, OrderedDict
def simulate_lfu_cache(capacity: int, ops: List[str], args: List[List[int]]) -> List[int]:
val_map = {}
freq_map = {}
buckets = defaultdict(OrderedDict)
min_freq = 0
results = []
def update_key_frequency(key: int) -> int:
cur_freq = freq_map[key]
del buckets[cur_freq][key]
if not buckets[cur_freq]:
del buckets[cur_freq]
new_freq = cur_freq + 1
freq_map[key] = new_freq
buckets[new_freq][key] = None
return cur_freq
for op, arg in zip(ops, args):
if op == "get":
key = arg[0]
if key in val_map:
old_f = update_key_frequency(key)
if min_freq == old_f and old_f not in buckets:
min_freq = old_f + 1
results.append(val_map[key])
else:
results.append(-1)
elif op == "put":
key, val = arg[0], arg[1]
if key in val_map:
val_map[key] = val
old_f = update_key_frequency(key)
if min_freq == old_f and old_f not in buckets:
min_freq = old_f + 1
else:
if len(val_map) >= capacity:
evict_bucket = buckets[min_freq]
evict_key, _ = evict_bucket.popitem(last=False)
if not evict_bucket:
del buckets[min_freq]
del val_map[evict_key]
del freq_map[evict_key]
val_map[key] = val
freq_map[key] = 1
buckets[1][key] = None
min_freq = 1
return results