Frequency-Based Cache Eviction
Data Structure DesignAuto-graded · 17 test casesLast updated
Build a cache that tracks access counts and evicts the least-used item, breaking ties by recency, all in constant time.
Implement a cache with a fixed capacity that evicts entries based on how often they have been accessed. The cache must support two operations, both running in O(1) average time:
- Retrieve a value by key: If the key exists, return its value and increment its access count. If the key does not exist, return
-1. - Insert or update a key-value pair: If the key already exists, update its value and increment its access count. If the key is new and the cache is at capacity, remove the entry with the lowest access count. When multiple entries share the lowest count, remove the one that was accessed least recently among them.
Your implementation will be tested by calling a sequence of operations. The first operation initializes the cache with a given capacity. Subsequent operations are retrievals or insertions.
Input format: You will receive two parallel lists:
operations: a list of operation names:"LFUCache","get", or"put"arguments: a list of argument lists, one per operation"LFUCache"receives[capacity]"get"receives[key]"put"receives[key, value]
Output format: Return a list of results, one per operation:
"LFUCache"and"put"returnNone"get"returns the value (an integer) or-1
Constraints
0 ≤ capacity ≤ 10^40 ≤ key ≤ 10^50 ≤ value ≤ 10^9- At most
2 × 10^5operations in total - The first operation is always
"LFUCache"
Examples
Example 1
Input: frequency_cache(['LFUCache', 'put', 'put', 'get', 'put', 'get'], [[2], [1, 1], [2, 2], [1], [3, 3], [2]])
Output: [None, None, None, 1, None, -1]
Hints
Hint 1
Track both the value and the access count for each key using a hash map.
Hint 2
Group keys by their access count. Within each group, maintain insertion order so you can identify the least recently used key.
Hint 3
When a key's access count increases, move it from its current group to the next group. Track the minimum access count across all groups to make eviction fast.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
A frequency-based eviction cache must answer two questions efficiently:
-
What is the value and access count for a given key?
Use a hash mapkey → (value, count). -
Which key should be removed when the cache is full?
We need the key with the smallest access count. If several keys share that count, we need the one accessed longest ago within that group.
The solution maintains three data structures:
values: maps each key to its stored valuefrequencies: maps each key to its current access countgroups: maps each access count to an ordered collection of keys at that count, with the oldest access at the front
Python's OrderedDict provides hash-map lookup plus doubly-linked-list ordering. It supports O(1) deletion by key, O(1) append to the end, and O(1) removal from the front using popitem(last=False). This gives us the "keys in recency order" structure we need without manually coding linked-list nodes.
We also track min_frequency, the smallest access count currently present in the cache. This allows O(1) eviction.
Updating min_frequency in O(1):
min_frequency changes in only two cases:
- A new key is inserted. It starts with count 1, so
min_frequency = 1. - An existing key is accessed, moving from count
ftof + 1. If the bucket atfbecomes empty andf == min_frequency, thenmin_frequencybecomesf + 1. This is correct because the key we just promoted is now in bucketf + 1, guaranteeing that bucket is non-empty.
Eviction itself never requires recomputing min_frequency. Every eviction is immediately followed by an insertion, which resets min_frequency to 1. There is no need to scan for the next minimum.
Why this is correct:
- Lowest count is evicted.
min_frequencyalways equals the smallest count of any key, maintained by the two rules above. - Ties are broken by recency. Within a bucket, keys are appended in the order they last reached that count. The front of the bucket is the least recently accessed key among those with that count.
- Updates count as accesses. Inserting a new value for an existing key increments its count, just like a retrieval.
Edge cases:
capacity == 0: Insertions do nothing, and retrievals always return-1.- Missing keys: Return
-1without changing state. - Updating an existing key: Change the value and increment the count. Never evict, since the cache size has not changed.
- Empty buckets: Delete them so we never try to pop from an empty
OrderedDict. - Eviction order: Evict first, then insert the new key. Otherwise, the new key might be evicted immediately since it has count 1.
Complexity
- Time: O(1) average for both retrieval and insertion. Each operation performs a constant number of hash lookups and
OrderedDictoperations (insert, delete, pop). - Space: O(capacity). Each key appears once in
values, once infrequencies, and once in exactly one bucket ingroups. Empty buckets are deleted, so the number of buckets never exceeds the number of keys.
Solution
from collections import OrderedDict
from typing import List, Optional
def frequency_cache(operations, arguments):
results = []
capacity = 0
values = {}
frequencies = {}
groups = {}
min_frequency = 0
def promote(key):
nonlocal min_frequency
frequency = frequencies[key]
bucket = groups[frequency]
del bucket[key]
if not bucket:
del groups[frequency]
if min_frequency == frequency:
min_frequency = frequency + 1
new_frequency = frequency + 1
frequencies[key] = new_frequency
groups.setdefault(new_frequency, OrderedDict())[key] = None
for operation, args in zip(operations, arguments):
if operation == "LFUCache":
capacity = args[0]
values = {}
frequencies = {}
groups = {}
min_frequency = 0
results.append(None)
elif operation == "get":
key = args[0]
if key not in values:
results.append(-1)
else:
promote(key)
results.append(values[key])
elif operation == "put":
if len(args) == 1 and isinstance(args[0], list) and len(args[0]) == 2:
key, value = args[0]
elif len(args) >= 2:
key, value = args[0], args[1]
else:
results.append(None)
continue
if capacity > 0:
if key in values:
values[key] = value
promote(key)
else:
if len(values) == capacity:
bucket = groups[min_frequency]
evicted_key, _ = bucket.popitem(last=False)
del values[evicted_key]
del frequencies[evicted_key]
if not bucket:
del groups[min_frequency]
values[key] = value
frequencies[key] = 1
groups.setdefault(1, OrderedDict())[key] = None
min_frequency = 1
results.append(None)
return results