Analyzing Caching Systems
\n\n
I'm focused on the LFU cache system design. I've broken down the project: First, I defined the primary function. Then, I dug into get(key) and put(key) operations and how those might be implemented, including data structures and potential edge cases. I'm now exploring the tradeoffs of various implementation approaches and considering potential performance bottlenecks.
Designing Data Structures
\n\n
I'm now zeroing in on data structures. I've considered basic hash maps (fast access, no frequency), min-heaps (functional, but O(logN) ), and doubly-linked lists with hash maps (good for LRU, bad for frequency). The "bucket" approach, with a dictionary of linked lists, is looking promising. I'm visualizing how to maintain frequency buckets for O(1) updates and ensuring the LRU tie-breaker.
Implementing Eviction Logic
\n\n
My current thinking is focused on put(key, value) with the buckets approach. I've sketched out the min_freq maintenance; ensuring it updates properly on eviction, and on node frequency increases. I'm focusing on the interaction between key_map, freq_map, and the DLLs, including the edge case of adding a new item when the cache is at capacity, making sure I hit the correct list and correct node for eviction. The details of node re-ordering are coming into focus, now.
Implementing Get and Put
\n\n
I'm now implementing the get(key) and put(key, value) methods. I've got get almost ironed out; I'm focusing on the frequency update and the min_freq adjustment. Put is trickier, especially eviction and insertion. The "bucket" approach for frequency management seems very promising, and the use of a DLL inside each bucket guarantees my LRU tie-breaking with ease. I'm now testing edge cases of updates and evictions, specifically the min_freq maintenance.
Testing Edge Cases and Optimizations
\n\n
I'm now deep in testing. Specifically, I'm verifying the LFU implementation. The put and get operations seem to be behaving as expected. However, I am now focusing on corner cases: how well the min_freq variable behaves during evictions and frequency changes. I'm exploring memory usage, potential thread safety, and opportunities for further simplification, aiming for maximum efficiency and readability.
Coding the Core Functions
\n\n
My current thinking is focused on _update(node), as this is core to both get() and put(). I've completed coding the DLinkedList and Node structures to ensure proper handling of DLLs. I'm focusing on creating clean Python code, especially making sure my min_freq variable behaves correctly. Next, I will design a test plan that focuses on the edge cases of updates and evictions.
Implementing _update(node)
\n\n
I'm now fully focused on the _update(node) helper function. This is key for the whole system: Updating frequency, removing the node from the old bucket, incrementing the frequency, and putting the node into the new bucket. I am making certain that min_freq is correctly handled during the process to avoid any potential logic errors. Next up, is a full test plan.
To design an LFU (Least Frequently Used) cache with O(1) time complexity for both get and put operations, we cannot simply use a min-heap (which would be O(log N)).
Instead, we need a combination of two Hash Maps and a Doubly Linked List logic.
The Architecture
vals (Hash Map): Maps key → Node. This allows us to retrieve the value and metadata of a key in O(1).
counts (Hash Map): Maps frequency → Doubly Linked List.
- Each entry in this map holds a list of all keys that have the same usage frequency.
- We use a Doubly Linked List (DLL) so we can remove specific nodes in O(1) and add to the head in O(1).
- The DLL also handles the LRU (Least Recently Used) tie-breaking. New items go to the head; old items sit at the tail.
min_freq (Integer): Tracks the current minimum frequency in the cache. This tells us immediately which bucket in counts to look at when we need to evict an item.
Python Implementation
Here is the complete implementation without using high-level wrapper collections (like OrderedDict), building the Doubly Linked List manually to demonstrate the low-level logic.
class Node:
def __init__(self, key, val):
self.key = key
self.val = val
self.freq = 1
self.prev = None
self.next = None
class DLinkedList:
"""A wrapper for a doubly linked list."""
def __init__(self):
# Sentinel nodes simplify boundary checks
self.head = Node(None, None)
self.tail = Node(None, None)
self.head.next = self.tail
self.tail.prev = self.head
self.size = 0
def insert_head(self, node):
"""Add a node right after head."""
node.prev = self.head
node.next = self.head.next
self.head.next.prev = node
self.head.next = node
self.size += 1
def remove_node(self, node):
"""Remove an existing node."""
node.prev.next = node.next
node.next.prev = node.prev
self.size -= 1
def remove_tail(self):
"""Remove and return the last real node (LRU within this frequency)."""
if self.size == 0:
return None
tail_node = self.tail.prev
self.remove_node(tail_node)
return tail_node
class LFUCache:
def __init__(self, capacity: int):
self._capacity = capacity
self._size = 0
self._min_freq = 0
# Maps key -> Node
self._node_map = {}
# Maps frequency -> DLinkedList
self._freq_map = {}
def _update_freq(self, node):
"""
Helper to increment node frequency and move it
to the correct frequency list.
"""
# 1. Remove from current frequency list
freq = node.freq
self._freq_map[freq].remove_node(node)
# 2. If this was the specific list for min_freq and it's now empty,
# we must increment min_freq because the item moved up.
if self._min_freq == freq and self._freq_map[freq].size == 0:
self._min_freq += 1
# 3. Update node frequency
node.freq += 1
new_freq = node.freq
# 4. Add to new frequency list
if new_freq not in self._freq_map:
self._freq_map[new_freq] = DLinkedList()
self._freq_map[new_freq].insert_head(node)
def get(self, key: int) -> int:
if key not in self._node_map:
return -1
node = self._node_map[key]
self._update_freq(node)
return node.val
def put(self, key: int, value: int) -> None:
if self._capacity == 0:
return
if key in self._node_map:
# Key exists: update value and frequency
node = self._node_map[key]
node.val = value
self._update_freq(node)
else:
# Key does not exist: check capacity
if self._size == self._capacity:
# Evict LRU node from the min_freq list
min_list = self._freq_map[self._min_freq]
popped = min_list.remove_tail()
del self._node_map[popped.key]
self._size -= 1
# Create new node
new_node = Node(key, value)
self._node_map[key] = new_node
# New nodes always start with freq 1
if 1 not in self._freq_map:
self._freq_map[1] = DLinkedList()
self._freq_map[1].insert_head(new_node)
self._node_map[key] = new_node
self._min_freq = 1
self._size += 1
Usage Example
# Initialize LFU Cache with capacity 2
lfu = LFUCache(2)
lfu.put(1, 1) # cache=[1(cnt:1)]
lfu.put(2, 2) # cache=[2(cnt:1), 1(cnt:1)]
print(lfu.get(1)) # Returns 1. Cache state: 1(cnt:2), 2(cnt:1).
# 1 moved to freq list 2. min_freq is 1.
lfu.put(3, 3) # Cache is full. Must evict min_freq (1).
# Node 2 is at freq 1. Evict 2.
# Cache: [3(cnt:1), 1(cnt:2)]
print(lfu.get(2)) # Returns -1 (not found)
print(lfu.get(3)) # Returns 3. Cache: 3(cnt:2), 1(cnt:2)
lfu.put(4, 4) # Cache full. Both 1 and 3 have freq 2.
# Tie breaker: 1 was accessed earlier than 3?
# Actually, in put(3,3), min_freq reset to 1.
# But here, min_freq is 2.
# Logic: remove tail of freq_list[2].
# Since we accessed 3 recently, 1 is the tail.
# Evict 1. Cache: [4(cnt:1), 3(cnt:2)]
print(lfu.get(1)) # Returns -1
print(lfu.get(3)) # Returns 3
print(lfu.get(4)) # Returns 4
Key Logic Explanations
1. Tie-Breaking (LRU)
The DLinkedList class handles the tie-breaking automatically.
- When we
put a new item or get an existing item, we insert it at the Head of the linked list.
- When we need to evict from a specific frequency bucket, we remove from the Tail.
- Therefore, the tail always contains the item accessed least recently within that specific frequency group.
2. Why min_freq works
- When we add a new item (
put a non-existent key), the frequency is always 1. Therefore, min_freq is guaranteed to become 1.
- When we access an existing item (
get or put update), its frequency increments (F→F+1).
- If that item was the only item in the
min_freq bucket, the bucket becomes empty.
- Since the item moved to F+1, the new minimum frequency must be F.
3. Complexity Analysis
- Get: Hash map lookup is O(1). Removing a node from a DLL is O(1). Adding to a DLL is O(1).
- Put: Hash map lookup is O(1). If eviction is needed, we look up
freq_map[min_freq] (Hash map get ) and remove the tail (DLL operation ).