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.

Leetcode LFU Cache problem solution

Problem solution in Python.

class Freqnode:
    def __init__(self, count):
        self.count = count = None
        self.prev = None = collections.OrderedDict()
    def link(self, nextnode): = nextnode
        nextnode.prev = self
class LFUCache(object):
    def __init__(self, capacity):
        self.dict_key_to_freqnode = {}
        self.cap = capacity
        self.head = Freqnode(0) # link with a dummy tail

    def get(self, key):
        node = self.dict_key_to_freqnode.get(key)
        if node:
            value =[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)
    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 =
            lru_key =
            del self.dict_key_to_freqnode[lru_key[0]]
        if key in self.dict_key_to_freqnode:
            self._updateKey(key, value)
            self._getNextFreqnode(self.head, key, value)
    def _removeFreqnodeIfEmpty(self, fnode):
        if len( == 0:
    def _getNextFreqnode(self, fnode, key, value):
        # create a new node if the +1 count doesn't exist
        if != fnode.count + 1:
            node = Freqnode(fnode.count+1)
        self.dict_key_to_freqnode[key] =[key] = value

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);
   = tail;
            tail.prev = head;
        void add(Node node) {
   = node;
            node.prev = head;
   = node;
        void remove(Node node) {
   = node.prev;
        Node removeLast() {
            if (size > 0) {
                Node node = tail.prev;
                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;
        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;
        else {
            node = new Node(key, value);
            nodeMap.put(key, node);
            if (size == capacity) {
                DLList lastList = countMap.get(min);
            min = 1;
            DLList newList = countMap.getOrDefault(node.cnt, new DLList());
            countMap.put(node.cnt, newList);
    private void update(Node node) {
        DLList oldList = countMap.get(node.cnt);
        if (node.cnt == min && oldList.size == 0) min++; 
        DLList newList = countMap.getOrDefault(node.cnt, new DLList());
        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;
    void touch(KIPII::iterator it, int f){
        int key = it->first;
        if(record[f].size() == 0) record.erase(f);
        location[key] = record[f+1].begin();
    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;
            if(cache.size() == _capacity){
                int LFLR = record.begin()->second.back();
            cache[key] = {value, 1};
            location[key] = record[1].begin();