Design and implement a data structure for a Least Frequently Used (LFU) cache.
Implement the LFUCache class:
LFUCache(int capacity)
Initializes the object with the capacity of the data structure.int get(int key)
Gets the value of the key if the key exists in the cache. Otherwise, returns -1.void put(int key, int value)
Update the value of the key if present, or inserts the key if not already present. When the cache reaches its capacity, it should invalidate and remove the least frequently used key before inserting a new item. For this problem, when there is a tie (i.e., two or more keys with the same frequency), the least recently used key would be invalidated. To determine the least frequently used key, a use counter is maintained for each key in the cache. The key with the smallest use counter is the least frequently used key.
When a key is first inserted into the cache, its use counter is set to 1 (due to the put operation). The use counter for a key in the cache is incremented either a get or put operation is called on it.
import collections
class Node:
def __init__(self, key, value):
self.key = key
self.value = value
self.freq = 1
self.next = None
self.prev = None
class DoubleLinkedList:
def __init__(self):
self.sentinel = Node(None, None)
self.sentinel.prev = self.sentinel.next = self.sentinel
self.size = 0
def append(self, node):
"""Append the node to the front."""
node.next = self.sentinel.next
self.sentinel.next = node
node.prev = self.sentinel
node.next.prev = node
self.size += 1
def pop(self, node=None):
"""Pop a node from the list."""
if self.size == 0:
return
if node is None:
node = self.sentinel.prev
node.prev.next = node.next
node.next.prev = node.prev
node.prev = node.next = None
self.size -= 1
return node
class LFUCache:
def __init__(self, capacity: int):
self.capacity = capacity
self.size = 0
self.min_freq = 1
self.nodes = dict()
self.freq_to_nodes = collections.defaultdict(DoubleLinkedList)
def get(self, key: int) -> int:
node = self.nodes.get(key)
if node is None:
return -1
else:
self.freq_to_nodes[node.freq].pop(node)
if node.freq == self.min_freq and self.freq_to_nodes[node.freq].size == 0:
self.min_freq += 1
node.freq += 1
self.freq_to_nodes[node.freq].append(node)
return node.value
def put(self, key: int, value: int) -> None:
if self.capacity == 0:
return
if key in self.nodes:
node = self.nodes[key]
self.freq_to_nodes[node.freq].pop(node)
if node.freq == self.min_freq and self.freq_to_nodes[node.freq].size == 0:
self.min_freq += 1
node.freq += 1
self.freq_to_nodes[node.freq].append(node)
node.value = value
return
if self.size == self.capacity:
node = self.freq_to_nodes[self.min_freq].pop()
self.nodes.pop(node.key)
self.size -= 1
node = Node(key, value)
self.nodes[key] = node
self.min_freq = node.freq
self.freq_to_nodes[node.freq].append(node)
self.size += 1