DSA

LFU Cache

Stacks & Queues. Time O(1).

August 8, 2026

Design a data structure that follows the constraints of a Least Recently Used (LRU) cache.

Implement the LRUCache class:

  • LRUCache(int capacity) Initialize the LRU cache with positive size capacity.
  • int get(int key) Return the value of the key if the key exists, otherwise return -1.
  • void put(int key, int value) Update the value of the key if the key exists. Otherwise, add the key-value pair to the cache. If the number of keys exceeds the capacity from this operation, evict the least recently used key. The functions get and put must each run in O(1) average time complexity.

Practice Link

Approach#

LFU (Least Frequently Used) requires evicting the key accessed the fewest times, with ties broken by recency. The O(1) solution uses three maps: (1) key → {value, freq} for direct lookup, (2) freq → doubly-linked list of keys (most-recent at front) so we can find and remove a candidate in O(1), and (3) key → list-iterator so we can reposition a key in its frequency list instantly. We also maintain minFreq — the current minimum frequency. On any get or put, the accessed key's frequency is incremented, it is moved from freqMap[oldFreq] to freqMap[newFreq], and minFreq is updated accordingly. On eviction, the least-recently-used key inside freqMap[minFreq] (the back of that list) is removed.

C++ Implementation#