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.
The functions get and put must each run in O(1) average time complexity.
class EntryDataType:
def __init__(self, key=None, value=None):
self.key = key
self.value = value
class Node:
def __init__(self, val=None):
self.prev = None
self.next = None
self.val = val
class DBList:
def __init__(self):
self.size = 0
self.dummy = Node()
self.dummy.next = self.dummy
self.dummy.prev = self.dummy
def append(self, node):
node.prev = self.dummy.prev
node.next = self.dummy
self.dummy.prev.next = node
self.dummy.prev = node
def remove(self, node):
node.prev.next = node.next
node.next.prev = node.prev
node.prev = None
node.next = None
return node
def empty(self):
return self.dummy.next == self.dummy
def pop_left(self):
return self.remove(self.dummy.next)
class LFUCache:
def __init__(self, capacity: int):
self.data = {}
self.freq = collections.defaultdict(int)
self.freq_tree = collections.defaultdict(DBList)
self.min_freq = 0
self.cap = capacity
self.size = 0
def _update(self, key):
freq = self.freq[key]
self.freq[key] += 1
node = self.data[key]
self.freq_tree[freq].remove(node)
self.freq_tree[freq + 1].append(node)
if freq == self.min_freq and self.freq_tree[freq].empty():
self.min_freq += 1
def get(self, key: int) -> int:
if key not in self.data:
return -1
self._update(key)
return self.data[key].val.value
def put(self, key: int, value: int) -> None:
if self.cap == 0:
return
if key not in self.data:
if self.size == self.cap:
delete_key = self.freq_tree[self.min_freq].pop_left().val.key
self.size -= 1
del self.freq[delete_key]
del self.data[delete_key]
self.min_freq = 1
self.freq[key] = 1
node = Node(EntryDataType(key, value))
self.freq_tree[1].append(node)
self.data[key] = node
self.size += 1
else:
self.data[key].val.value = value
self._update(key)