Library

Volume 3 · Coding Problems & Data Structures

Notebook
Sign in

Section 19

LFU Cache Implementation (Full Working Code)

650 words · about 3 min

Concept: Evicts the item with the lowest access frequency; ties broken by least-recently-used. Requires: key→value map, key→frequency map, and frequency→ordered-keys buckets, plus tracking of the current minimum frequency.

Python Implementation

from collections import defaultdict, OrderedDict


class LFUCache:
    """
    O(1) get/put LFU cache.

    freq_to_keys[f] is an OrderedDict acting as an ordered set —
    insertion order gives LRU-tiebreak within the same frequency.
    """

    def __init__(self, capacity: int):
        if capacity <= 0:
            raise ValueError("Capacity must be positive")
        self.capacity = capacity
        self.key_to_val: dict[int, int] = {}
        self.key_to_freq: dict[int, int] = {}
        self.freq_to_keys: dict[int, OrderedDict] = defaultdict(OrderedDict)
        self.min_freq = 0

    def get(self, key: int) -> int:
        if key not in self.key_to_val:
            return -1
        self._touch(key)
        return self.key_to_val[key]

    def put(self, key: int, value: int) -> None:
        if self.capacity == 0:
            return

        if key in self.key_to_val:
            self.key_to_val[key] = value
            self._touch(key)
            return

        if len(self.key_to_val) >= self.capacity:
            evict_key, _ = self.freq_to_keys[self.min_freq].popitem(last=False)
            del self.key_to_val[evict_key]
            del self.key_to_freq[evict_key]

        self.key_to_val[key] = value
        self.key_to_freq[key] = 1
        self.freq_to_keys[1][key] = None
        self.min_freq = 1

    def _touch(self, key: int) -> None:
        freq = self.key_to_freq[key]
        del self.freq_to_keys[freq][key]

        if not self.freq_to_keys[freq] and freq == self.min_freq:
            self.min_freq += 1

        self.key_to_freq[key] = freq + 1
        self.freq_to_keys[freq + 1][key] = None


# --- Usage ---
lfu = LFUCache(2)
lfu.put(1, 1)
lfu.put(2, 2)
lfu.get(1)        # freq(1)=2
lfu.put(3, 3)      # evicts key 2 (freq=1, LFU)
assert lfu.get(2) == -1
assert lfu.get(3) == 3

C# Implementation

using System;
using System.Collections.Generic;

public class LFUCache
{
    private readonly int _capacity;
    private readonly Dictionary<int, int> _keyToVal = new();
    private readonly Dictionary<int, int> _keyToFreq = new();
    private readonly Dictionary<int, LinkedList<int>> _freqToKeys = new();
    private readonly Dictionary<int, LinkedListNode<int>> _keyToNode = new();
    private int _minFreq;

    public LFUCache(int capacity)
    {
        _capacity = capacity;
    }

    public int Get(int key)
    {
        if (!_keyToVal.TryGetValue(key, out var value)) return -1;
        Touch(key);
        return value;
    }

    public void Put(int key, int value)
    {
        if (_capacity == 0) return;

        if (_keyToVal.ContainsKey(key))
        {
            _keyToVal[key] = value;
            Touch(key);
            return;
        }

        if (_keyToVal.Count >= _capacity)
        {
            var list = _freqToKeys[_minFreq];
            var evictKey = list.First!.Value;
            list.RemoveFirst();
            _keyToVal.Remove(evictKey);
            _keyToFreq.Remove(evictKey);
            _keyToNode.Remove(evictKey);
        }

        _keyToVal[key] = value;
        _keyToFreq[key] = 1;
        if (!_freqToKeys.TryGetValue(1, out var freqList))
        {
            freqList = new LinkedList<int>();
            _freqToKeys[1] = freqList;
        }
        _keyToNode[key] = freqList.AddLast(key);
        _minFreq = 1;
    }

    private void Touch(int key)
    {
        var freq = _keyToFreq[key];
        var oldList = _freqToKeys[freq];
        oldList.Remove(_keyToNode[key]);

        if (oldList.Count == 0 && freq == _minFreq)
        {
            _minFreq++;
        }

        var newFreq = freq + 1;
        _keyToFreq[key] = newFreq;
        if (!_freqToKeys.TryGetValue(newFreq, out var newList))
        {
            newList = new LinkedList<int>();
            _freqToKeys[newFreq] = newList;
        }
        _keyToNode[key] = newList.AddLast(key);
    }
}

Complexity

Operation Time Space
Get / Put O(1) O(capacity)

Follow-up: LFU is more complex than LRU because access patterns with short bursts can “pollute” the cache with high-frequency-but-now-irrelevant keys. In production, consider W-TinyLFU (used by Caffeine cache in Java) which combines a frequency sketch with an admission policy — new items must prove they’re “worth” evicting an existing item.