- Decide the key that represents the information needed later.
- Update its count or stored state while scanning the input.
- Use constant-time expected lookups to detect matches or assemble the result.
Code notes
- 69 lines of C++ from the credited upstream file 460.cpp.
- The implementation visibly relies on sequence storage, hash lookup.
- No explicit loop blocks detected.
Complexity
Expected hash operations are constant time, but the surrounding scan and the number of stored keys determine total work and memory.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1struct Node {2 int key;3 int value;4 int freq;5 list<int>::const_iterator it;6};7 8class LFUCache {9 public:10 LFUCache(int capacity) : capacity(capacity), minFreq(0) {}11 12 int get(int key) {13 const auto it = keyToNode.find(key);14 if (it == keyToNode.cend())15 return -1;16 17 Node& node = it->second;18 touch(node);19 return node.value;20 }21 22 void put(int key, int value) {23 if (capacity == 0)24 return;25 if (const auto it = keyToNode.find(key); it != keyToNode.cend()) {26 Node& node = it->second;27 node.value = value;28 touch(node);29 return;30 }31 32 if (keyToNode.size() == capacity) {33 34 const int keyToEvict = freqToList[minFreq].back();35 freqToList[minFreq].pop_back();36 keyToNode.erase(keyToEvict);37 }38 39 minFreq = 1;40 freqToList[1].push_front(key);41 keyToNode[key] = {key, value, 1, freqToList[1].cbegin()};42 }43 44 private:45 int capacity;46 int minFreq;47 unordered_map<int, Node> keyToNode;48 unordered_map<int, list<int>> freqToList;49 50 void touch(Node& node) {51 52 const int prevFreq = node.freq;53 const int newFreq = ++node.freq;54 55 56 freqToList[prevFreq].erase(node.it);57 if (freqToList[prevFreq].empty()) {58 freqToList.erase(prevFreq);59 60 if (prevFreq == minFreq)61 ++minFreq;62 }63 64 65 freqToList[newFreq].push_front(node.key);66 node.it = freqToList[newFreq].cbegin();67 }68};69