Leetcode LFU Cache problem solution YASH PAL, 31 July 2024 In this Leetcode LFU Cache problem solution 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. Problem solution in Python. class Freqnode: def __init__(self, count): self.count = count self.next = None self.prev = None self.kids = collections.OrderedDict() def link(self, nextnode): self.next = nextnode nextnode.prev = self class LFUCache(object): def __init__(self, capacity): self.dict_key_to_freqnode = {} self.cap = capacity self.head = Freqnode(0) self.head.link(Freqnode(0)) # link with a dummy tail def get(self, key): node = self.dict_key_to_freqnode.get(key) if node: value = node.kids[key] self._updateKey(key, value) return value return -1 def _updateKey(self, key, value): oldfnode = self.dict_key_to_freqnode[key] newfnode = self._getNextFreqnode(oldfnode, key, value) del oldfnode.kids[key] self._removeFreqnodeIfEmpty(oldfnode) def set(self, key, value): if self.cap == 0: return if len(self.dict_key_to_freqnode) == self.cap and key not in self.dict_key_to_freqnode: # reaching cap, need to kick out least recently used key with the least frequent use count. node = self.head.next lru_key = node.kids.popitem(False) del self.dict_key_to_freqnode[lru_key[0]] self._removeFreqnodeIfEmpty(node) if key in self.dict_key_to_freqnode: self._updateKey(key, value) else: self._getNextFreqnode(self.head, key, value) def _removeFreqnodeIfEmpty(self, fnode): if len(fnode.kids) == 0: fnode.prev.link(fnode.next) def _getNextFreqnode(self, fnode, key, value): # create a new node if the +1 count doesn't exist if fnode.next.count != fnode.count + 1: node = Freqnode(fnode.count+1) node.link(fnode.next) fnode.link(node) self.dict_key_to_freqnode[key] = fnode.next fnode.next.kids[key] = value return fnode.next Problem solution in Java. public class LFUCache { class Node { int key, val, cnt; Node prev, next; Node(int key, int val) { this.key = key; this.val = val; cnt = 1; } } class DLList { Node head, tail; int size; DLList() { head = new Node(0, 0); tail = new Node(0, 0); head.next = tail; tail.prev = head; } void add(Node node) { head.next.prev = node; node.next = head.next; node.prev = head; head.next = node; size++; } void remove(Node node) { node.prev.next = node.next; node.next.prev = node.prev; size--; } Node removeLast() { if (size > 0) { Node node = tail.prev; remove(node); return node; } else return null; } } int capacity, size, min; Map<Integer, Node> nodeMap; Map<Integer, DLList> countMap; public LFUCache(int capacity) { this.capacity = capacity; nodeMap = new HashMap<>(); countMap = new HashMap<>(); } public int get(int key) { Node node = nodeMap.get(key); if (node == null) return -1; update(node); return node.val; } public void put(int key, int value) { if (capacity == 0) return; Node node; if (nodeMap.containsKey(key)) { node = nodeMap.get(key); node.val = value; update(node); } else { node = new Node(key, value); nodeMap.put(key, node); if (size == capacity) { DLList lastList = countMap.get(min); nodeMap.remove(lastList.removeLast().key); size--; } size++; min = 1; DLList newList = countMap.getOrDefault(node.cnt, new DLList()); newList.add(node); countMap.put(node.cnt, newList); } } private void update(Node node) { DLList oldList = countMap.get(node.cnt); oldList.remove(node); if (node.cnt == min && oldList.size == 0) min++; node.cnt++; DLList newList = countMap.getOrDefault(node.cnt, new DLList()); newList.add(node); countMap.put(node.cnt, newList); } } Problem solution in C++. class LFUCache { typedef list<int> LI; typedef unordered_map<int, LI::iterator> PII; //From key to iterator in LI; typedef map<int, LI> ILI; //From frequency to a list of keys; typedef unordered_map<int, pair<int, int>> KIPII; //From key to value and frequency; KIPII cache; PII location; ILI record; int _capacity; public: void touch(KIPII::iterator it, int f){ int key = it->first; record[f].erase(location[key]); if(record[f].size() == 0) record.erase(f); record[f+1].push_front(key); location[key] = record[f+1].begin(); return; } LFUCache(int capacity) { _capacity = capacity; } int get(int key) { if(_capacity == 0) return -1; auto it = cache.find(key); if(it == cache.end()) return -1; touch(it, it->second.second); it->second.second += 1; return it->second.first; } void put(int key, int value) { if(_capacity == 0) return; auto it = cache.find(key); if(it != cache.end()){ it->second.first = value; touch(it, it->second.second); it->second.second += 1; } else{ if(cache.size() == _capacity){ int LFLR = record.begin()->second.back(); record.begin()->second.pop_back(); cache.erase(LFLR); location.erase(LFLR); } cache[key] = {value, 1}; record[1].push_front(key); location[key] = record[1].begin(); } return; } }; coding problems