Designing LFU Cache System
The user asked about building a caching system with an LFU eviction policy, but they haven't specified the language. They might expect an explanation and some code examples. I need to ask clarifying questions but could also choose a common language like Python or Java to keep it concise. I’ll propose a design using two hash maps and a frequency map, plus a doubly-linked list or OrderedDict. The implementation should cover setting capacity, getting, and putting keys while ensuring efficient eviction.Drafting LFU Cache Implementation
I’m outlining the process for updating frequencies in the LFU cache: when incrementing, I’ll remove the key from the old frequency and add it to the new frequency list. If I need to put a key, I'll check capacity first. If it’s reached, I’ll evict the least frequently used key. I also want to provide a class interface and include complexity considerations. I plan to summarize the design, then show a Python implementation with a small usage example and tests, keeping the response concise. Below is a standard O(1)-time LFU cache implementation using Python.
If you want it in another language (Java, C++, etc.), I can translate.
Design
Operations:
get(key) -> value or -1
put(key, value)
Eviction policy:
- Remove the key with the lowest frequency.
- If multiple keys share the same frequency, remove the oldest (LRU among that frequency).
Data structures:
-
key_to_val_freq:
key -> (value, frequency)
-
freq_to_keys:
frequency -> OrderedDict of keys
(OrderedDict allows O(1) insert, delete, and finding the oldest key.)
-
min_freq:
Current minimum frequency in the cache, to know where to evict from.
All operations are O(1) average time.
Implementation (Python)
from collections import defaultdict, OrderedDict
class LFUCache:
def __init__(self, capacity: int):
self.capacity = capacity
self.size = 0
# key -> (value, freq)
self.key_to_val_freq = {}
# freq -> OrderedDict of keys (to get LRU among same freq)
self.freq_to_keys = defaultdict(OrderedDict)
# minimum frequency of any key in the cache
self.min_freq = 0
def _update_freq(self, key: int):
"""Internal helper to increment the frequency of a key."""
value, freq = self.key_to_val_freq[key]
# Remove from old frequency bucket
del self.freq_to_keys[freq][key]
if not self.freq_to_keys[freq]:
del self.freq_to_keys[freq]
if self.min_freq == freq:
self.min_freq += 1
# Add to new frequency bucket
new_freq = freq + 1
self.freq_to_keys[new_freq][key] = None
self.key_to_val_freq[key] = (value, new_freq)
def get(self, key: int) -> int:
if key not in self.key_to_val_freq:
return -1
self._update_freq(key)
return self.key_to_val_freq[key][0]
def put(self, key: int, value: int) -> None:
if self.capacity == 0:
return
# If key already exists, update value and freq
if key in self.key_to_val_freq:
_, freq = self.key_to_val_freq[key]
self.key_to_val_freq[key] = (value, freq)
self._update_freq(key)
return
# If at capacity, evict LFU key
if self.size == self.capacity:
# get LFU frequency's LRU key
lfu_keys = self.freq_to_keys[self.min_freq]
evict_key, _ = lfu_keys.popitem(last=False) # pop oldest
if not lfu_keys:
del self.freq_to_keys[self.min_freq]
del self.key_to_val_freq[evict_key]
self.size -= 1
# Insert new key with frequency 1
self.key_to_val_freq[key] = (value, 1)
self.freq_to_keys[1][key] = None
self.min_freq = 1
self.size += 1
Example Usage
cache = LFUCache(2)
cache.put(1, 1) # cache: {1:1}
cache.put(2, 2) # cache: {1:1, 2:2}
print(cache.get(1)) # returns 1, freq(1)=2, freq(2)=1
cache.put(3, 3)
# Evicts key 2 (freq:1, LFU). cache: {1:1 (freq=2), 3:3 (freq=1)}
print(cache.get(2)) # returns -1 (not found)
print(cache.get(3)) # returns 3 (freq(3)=2)
cache.put(4, 4)
# Now key 1 and 3 both freq=2; evict oldest among them -> key 1
# cache: {3:3, 4:4}
print(cache.get(1)) # -1
print(cache.get(3)) # 3
print(cache.get(4)) # 4
If you tell me your target language or framework (e.g., Java with interfaces, Node.js, a web service, etc.), I can adapt this into a full component that plugs into your system.