The user wants a caching system with a Least Frequently Used (LFU) eviction policy.
I need to provide a clear, well-documented, and functional implementation of an LFU cache.
Requirements Analysis:
-
Core Functionality:
get(key): Retrieve an item. If it exists, return the value and update its frequency. If not, return a specific indicator (e.g., -1 or null).
put(key, value): Add an item.
- If the key exists, update the value and frequency.
- If the key doesn't exist:
- If the cache is full, evict the LFU item.
- Add the new item with frequency 1.
-
Time Complexity Constraints:
- Both
get and put operations should ideally run in O(1) time complexity. This is the standard expected from a "production-ready" or interview-standard LFU cache implementation.
-
Data Structures needed for O(1) LFU:
- We need to track frequency.
- We need to track the order of insertion within a specific frequency (to handle ties: Least Recently Used among the Least Frequently Used).
- Map 1 (Key -> Node): A hash map to store key-value pairs along with their frequency. This allows O(1) access.
- Map 2 (Frequency -> List of Keys): A hash map where keys are frequencies and values are Double Linked Lists (or Ordered Sets) of keys that share that frequency. This allows O(1) access to the head/tail of a frequency group.
- Variable
min_freq: An integer to track the current minimum frequency in the cache. This is crucial for O(1) eviction. Without this, we'd have to scan for the minimum, taking O(N).
-
Algorithm Details:
-
get(key):
- Check
KeyMap. If missing, return -1.
- If found:
- Get the node (value, freq).
- Update frequency:
freq++.
- Move the node from the
freq list to the freq + 1 list in FreqMap.
- Update
min_freq: If the freq list becomes empty and freq was min_freq, increment min_freq.
- Return value.
-
put(key, value):
- If
key exists:
- Update value in
KeyMap.
- Call
get(key) logic (or equivalent update function) to bump frequency.
- If
key doesn't exist:
- If cache is full:
- Get the list at
min_freq.
- Remove the least recently used item (tail of the list) from both the list and
KeyMap.
- Add new node with
freq = 1.
- Add to
KeyMap.
- Add to
FreqMap at index 1.
- Reset
min_freq to 1.
-
Language Selection:
- Python is generally the most readable for algorithmic demonstrations. I will use Python.
- I need to implement a helper Double Linked List (DLL) class because Python's standard
collections.OrderedDict is good, but a custom DLL often makes the pointer manipulation clearer for educational purposes. However, collections.OrderedDict in Python 3.7+ preserves insertion order and has move_to_end and popitem(last=False). Using OrderedDict is often the most "Pythonic" and concise way to solve this, but strictly speaking, implementing a DLL from scratch demonstrates understanding of the underlying mechanism.
- Decision: I will provide the implementation using Python's
collections.OrderedDict because it simulates the DLL behavior required for the "LRU among LFU" logic efficiently and concisely. It makes the code much shorter and easier to read without sacrificing the O(1) logic explanation.
-
Refining the Implementation Plan (Python OrderedDict approach):
-
key_map: key -> (value, frequency)
-
freq_map: frequency -> OrderedDict(keys)
-
min_freq: integer
-
Helper function update(key, value): (Used by both get and put)
- Get
(v, f) from key_map.
- Delete key from
freq_map[f].
- If
freq_map[f] is empty:
- Delete
f from freq_map.
- If
f == min_freq, min_freq++.
- Update
key_map with (value, f+1).
- Add key to
freq_map[f+1].
-
Code Structure:
- Class
LFUCache
__init__(capacity)
get(key)
put(key, value)
-
Edge Cases:
- Capacity 0 (should handle gracefully).
- Updating an existing key (frequency updates, value updates).
- Eviction logic when multiple keys have the same frequency (LRU logic).
-
Writing the Code (Mental Draft):
from collections import defaultdict, OrderedDict
class LFUCache:
def __init__(self, capacity):
self.cap = capacity
self.key_to_val_freq = {} # key -> (val, freq)
self.freq_to_keys = defaultdict(OrderedDict) # freq -> OrderedDict(key -> None)
self.min_freq = 0
def get(self, key):
if key not in self.key_to_val_freq: return -1
val, freq = self.key_to_val_freq[key]
# Logic to move from freq bucket to freq+1 bucket
# ...
return val
def put(self, key, value):
# ...
-
Reviewing Complexity:
get: Dict lookup O(1), OrderedDict deletion/insertion O(1). Total O(1).
put: Dict lookup O(1), OrderedDict deletion/insertion . Total .
-
Adding Documentation/Explanation:
- Explain why we need two hash maps.
- Explain the "LRU within LFU" tie-breaking rule.
- Explain the O(1) requirement.
-
Final Polish: I will structure the response with:
- A high-level explanation of the logic.
- The Python code implementation.
- Example usage.
- A brief analysis of time and space complexity.
Let's write the actual Python code logic clearly.
- Inside
get:
val, freq = self.key_to_val_freq[key]
del self.freq_to_keys[freq][key]
- Check empty bucket logic.
self.freq_to_keys[freq+1][key] = None (or just insert)
self.key_to_val_freq[key] = (val, freq+1)
- Inside
put:
- If cap <= 0 return.
- If key exists: update val, call update logic.
- If full: evict.
lfu_key = self.freq_to_keys[self.min_freq].popitem(last=False)[0]. del self.key_to_val_freq[lfu_key].
- Insert new:
min_freq = 1, freq_to_keys[1][key] = None, key_to_val_freq[key] = (value, 1).
Wait, strictly speaking, OrderedDict values don't matter much for the LRU part, but we can store the value there if we want to merge structures. However, keeping key_to_val separate from the frequency lists is cleaner conceptually.
Actually, storing (value, freq) in one map and just keys in the frequency map is the standard design.
Let's refine the "update" logic to avoid code duplication.
Self-Correction during drafting:
Should I implement a Doubly Linked List manually?
Pros: No reliance on specific library features (like OrderedDict internals), transferable knowledge to C++/Java.
Cons: Verbose in Python.
Decision: I will use collections.OrderedDict because it acts as a built-in Hash Map + Linked List. It effectively demonstrates the logic without 50 lines of Node class boilerplate. I will explicitly state that OrderedDict is being used to handle the "LRU" aspect.
Let's double check the min_freq logic.
- New insert ->
min_freq = 1. Always.
- Access (get/put update):
- Old freq
f. New freq f+1.
- If
f == min_freq AND freq_to_keys[f] becomes empty -> min_freq = f + 1.
- If
freq_to_keys[f] is not empty, min_freq stays.
This implementation achieves O(1) (constant time) complexity for both get and put operations. It uses a combination of Hash Maps (Dictionaries) and Doubly Linked Lists to track frequency and usage order.
Design Logic
To achieve O(1), we use three main structures:
- Key-Value Map: Stores
Key -> Node (containing value and frequency).
- Frequency Map: Stores
Frequency -> Linked List of Nodes. This allows us to group items by how often they are accessed.
- Minimum Frequency Variable: Tracks the current minimum frequency. When eviction is needed, we remove the Least Recently Used (LRU) item from the Least Frequently Used (LFU) frequency list.
Python Implementation
import collections
class Node:
"""
A Doubly Linked List Node.
"""
def __init__(self, key, value):
self.key = key
self.value = value
self.freq = 1
self.prev = None
self.next = None
class DLinkedList:
"""
A standard Doubly Linked List to handle O(1) additions and removals.
We use it to implement LRU logic within a specific frequency bucket.
"""
def __init__(self):
self.head = Node(0, 0) # Dummy head
self.tail = Node(0, 0) # Dummy tail
self.head.next = self.tail
self.tail.prev = self.head
self.size = 0
def append(self, node):
"""
Add node to the front (most recently used position).
Head <-> Node <-> ...
"""
node.prev = self.head
node.next = self.head.next
self.head.next.prev = node
self.head.next = node
self.size += 1
def remove(self, node):
"""
Remove a specific node from the list.
"""
node.prev.next = node.next
node.next.prev = node.prev
self.size -= 1
def pop_last(self):
"""
Remove and return the last node (least recently used).
Returns None if list is empty.
"""
if self.size == 0:
return None
node = self.tail.prev
self.remove(node)
return node
class LFUCache:
def __init__(self, capacity: int):
self.capacity = capacity
self.size = 0
self.min_freq = 0
# Key -> Node mapping for O(1) access
self.cache = {}
# Freq -> DLinkedList mapping
# Nodes with same frequency are stored in a linked list (LRU order)
self.freq_map = collections.defaultdict(DLinkedList)
def _update(self, node):
"""
Internal helper:
1. Increase frequency of the node.
2. Move node to the new frequency list.
3. Update min_freq if necessary.
"""
freq = node.freq
# Remove node from current frequency list
self.freq_map[freq].remove(node)
# If the old frequency list is now empty and it was the min_freq,
# we must increment min_freq because the node we just updated
# is now the only one (or part of) the next freq level.
if self.min_freq == freq and self.freq_map[freq].size == 0:
self.min_freq += 1
# Increment frequency
node.freq += 1
freq = node.freq
# Add node to the new frequency list (at the front/MRU position)
self.freq_map[freq].append(node)
def get(self, key: int) -> int:
if key not in self.cache:
return -1
node = self.cache[key]
self._update(node)
return node.value
def put(self, key: int, value: int) -> None:
if self.capacity == 0:
return
if key in self.cache:
# Key exists: update value and frequency
node = self.cache[key]
self._update(node)
node.value = value
else:
# Key does not exist
if self.size == self.capacity:
# Cache is full: Evict LFU item (LRU within LFU)
# The pop_last method removes the LRU item from the min_freq list
node_to_remove = self.freq_map[self.min_freq].pop_last()
del self.cache[node_to_remove.key]
self.size -= 1
# Add new node
new_node = Node(key, value)
self.cache[key] = new_node
# New nodes always have frequency 1
self.freq_map[1].append(new_node)
# Reset min_freq to 1
self.min_freq = 1
self.size += 1
How to Run and Test
Here is a script to verify the functionality. It mimics standard LFU behavior where ties in frequency are broken by LRU (Least Recently Used).
# --- Usage Example ---
print("Initializing LFU Cache with Capacity 2...")
cache = LFUCache(2)
cache.put(1, 10) # Cache: {1=10}, Freq: {1: 1}
cache.put(2, 20) # Cache: {1=10, 2=20}, Freq: {1: 1, 2: 1}
print(f"Get 1: {cache.get(1)}") # Returns 10. Cache: {2=20, 1=10}, Freq: {2: 1, 1: 2}
cache.put(3, 30) # Evicts key 2 (Frequency 1, LRU). Cache: {1=10, 3=30}
print(f"Get 2: {cache.get(2)}") # Returns -1 (not found)
print(f"Get 3: {cache.get(3)}") # Returns 30. Freq: {1: 2, 3: 2}
cache.put(4, 40) # Evicts key 1 (Both 1 and 3 have freq 2, but 1 was accessed earlier/older LRU). Cache: {3=30, 4=40}
print(f"Get 1: {cache.get(1)}") # Returns -1 (not found)
print(f"Get 3: {cache.get(3)}") # Returns 30. Freq: {3: 3, 4: 1}
print(f"Get 4: {cache.get(4)}") # Returns 40. Freq: {3: 3, 4: 2}
Complexity Analysis
-
Time Complexity: O(1) for both Get and Put
- Get: Hash map lookup is O(1). Updating the node (removing from one linked list and adding to another) is O(1).
- Put: Hash map insertion is O(1). If eviction is needed, removing the tail of the doubly linked list is . Adding the new node is .