Simulate LFU Cache Sequence
Data Structure DesignAuto-graded · 19 test casesLast updated
Process a series of LFU cache queries with LRU tie-breaking and track the output of each operation.
Design and process a sequence of operations on a Least Frequently Used (LFU) cache.
The cache starts empty with a non-negative integer capacity and supports two types of operations:
-
"get": Takes[key].- If
keyis present in the cache, its frequency count increases by 1, and its access time is updated to be the most recent. Returns the associated value. - If
keyis missing, returns-1. Frequency counts are unaffected.
- If
-
"put": Takes[key, value].- If
keyalready exists, update its associated value tovalue. Its access frequency increases by 1, and it is marked as the most recently accessed. - If
keyis not present:- If the cache has reached maximum capacity, evict the key with the lowest frequency. If multiple keys share the lowest frequency, evict the least recently used (LRU) key among them.
- Insert the new
keywithvalue. Set its initial frequency to 1, and mark it as the most recently accessed key.
- A
"put"operation produces no direct return value (represented asNone).
- If
If capacity is 0, no keys can be stored. Any "put" operation is discarded (returns None), and any "get" operation returns -1.
Given capacity, a list of operation names operations, and a list of corresponding parameter arrays arguments, process the operations in order and return a list containing the output of each operation.
Constraints
0 <= capacity <= 10^41 <= len(operations) == len(arguments) <= 10^5- Each string in
operationsis either"get"or"put". - For
"get",arguments[i]has length 1:[key]. - For
"put",arguments[i]has length 2:[key, value]. - All keys and values are integers in the range
[0, 10^9].
Examples
Example 1
Input: lfu_cache(2, ['put', 'put', 'get', 'put', 'get', 'get'], [[1, 1], [2, 2], [1], [3, 3], [2], [3]])
Output: [None, None, 1, None, -1, 3]
Example 2
Input: lfu_cache(2, ['put', 'put', 'put', 'get', 'put', 'get', 'get', 'put', 'get', 'get', 'get'], [[1, 1], [2, 2], [3, 3], [1], [4, 4], [2], [3], [5, 5], [1], [3], [4]])
Output: [None, None, None, -1, None, -1, 3, None, -1, 3, -1]
Example 3
Input: lfu_cache(0, ['put', 'get', 'put', 'get'], [[1, 1], [1], [2, 2], [2]])
Output: [None, -1, None, -1]
Hints
Hint 1
Map each key to both its stored value and its frequency.
Hint 2
Maintain a map from frequency to a doubly-linked list or an OrderedDict of keys to retain recency order for tie-breaking.
Hint 3
Keep track of the minimum frequency currently in the cache (`min_freq`) to achieve O(1) time for evictions.
Worked solution
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Method Explanation
To handle both LFU eviction and LRU tie-breaking in $O(1)$ average time per operation:
- Key-Value & Key-Frequency Storage: Maintain hash maps for key-to-value lookup and key-to-frequency lookup.
- Frequency Buckets: Maintain a hash map mapping each frequency
fto anOrderedDictof keys. In Python, anOrderedDictpreserves insertion order, allowing us to treat the front of the dictionary as the least recently used key and the back as the most recently used key. - Minimum Frequency Tracking: Store an integer
min_frequencyrepresenting the current minimum frequency of any key present in the cache.
When a key is accessed or updated ("touched"):
- Its current frequency
fis retrieved, and it is removed fromkeys_by_frequency[f]. - If
keys_by_frequency[f]becomes empty andmin_frequency == f, incrementmin_frequencyby 1. - Its frequency is updated to
f + 1, and it is appended tokeys_by_frequency[f + 1].
When a new key is inserted via "put":
- If the cache is full (
len(values) >= capacity), identify the LRU key among the least frequent by popping the oldest element fromkeys_by_frequency[min_frequency]. Remove it from the cache maps. - Insert the new key with frequency 1 and set
min_frequency = 1.
Complexity Analysis
- Time Complexity: $O(1)$ amortized per operation. Dictionary lookups, deletions, and insertions in
OrderedDictare all $O(1)$. Thus, executing $N$ operations takes $O(N)$ total time. - Space Complexity: $O(\text{capacity})$ auxiliary space to store the key-value mappings, frequency counts, and ordered dictionaries.
Python Reference Solution
from collections import defaultdict, OrderedDict
from typing import List, Optional
def lfu_cache(capacity: int, operations: List[str], arguments: List[List[int]]) -> List[Optional[int]]:
values = {}
frequencies = {}
keys_by_frequency = defaultdict(OrderedDict)
min_frequency = 0
results = []
def touch(key: int) -> None:
nonlocal min_frequency
frequency = frequencies[key]
del keys_by_frequency[frequency][key]
if not keys_by_frequency[frequency]:
del keys_by_frequency[frequency]
if min_frequency == frequency:
min_frequency += 1
frequencies[key] = frequency + 1
keys_by_frequency[frequency + 1][key] = None
for operation, args in zip(operations, arguments):
if operation == "get":
key = args[0]
if key not in values:
results.append(-1)
else:
touch(key)
results.append(values[key])
elif operation == "put":
key, value = args
if capacity == 0:
results.append(None)
continue
if key in values:
values[key] = value
touch(key)
else:
if len(values) >= capacity:
evicted_key, _ = keys_by_frequency[min_frequency].popitem(last=False)
del values[evicted_key]
del frequencies[evicted_key]
if not keys_by_frequency[min_frequency]:
del keys_by_frequency[min_frequency]
values[key] = value
frequencies[key] = 1
keys_by_frequency[1][key] = None
min_frequency = 1
results.append(None)
else:
raise ValueError("unknown operation")
return results