Learn / Stacks and queues

LRU and LFU cache

An LRU cache keeps the most recently used items and drops the least recently used one when full. A hash map finds a key in O(1); a doubly linked list keeps the use order, so moving an item to the front and removing the last one are O(1). An LFU cache adds a list per use count.

How to recognise it

  • A fixed-capacity store must evict something when full.
  • Get and put must both be O(1).
  • The eviction rule depends on how recently (or how often) each item was used.

Two structures working together

NeedStructure
find a key in O(1)hash map from key to node
know the least recent in O(1)doubly linked list, most recent at the front
move an item to the front in O(1)unlink using prev and next, then insert after the head

Two dummy nodes, head and tail, remove every null check: the most recent item is head.next and the least recent is tail.prev.

get(key):  if key not in map: return -1
           move its node to the front; return its value
put(key, value):
           if key in map: update the value, move to the front, done
           if full: remove tail.prev from the list and from the map
           add a new node at the front and to the map

In C++, std::list with splice and a map of iterators does the same. In Java, LinkedHashMap with access order can do it in a few lines, but interviews usually want the list by hand.

LFU in one paragraph

Least frequently used evicts the item used the fewest times, breaking ties by least recent. Keep, for each use count, a list ordered by recency, and remember the smallest count. A use moves an item from list f to list f + 1. LFU has no problem in this guide's sheets, so this lesson stops there.

Common mistakes

  • Forgetting that a put on an existing key also counts as a use.
  • Evicting before checking whether the key already exists.
  • Not removing the evicted key from the map.

Problems

0 of 2 solved

Check yourself

Capacity 2: put 1, put 2, get 1, put 3. Which key is evicted?

Why a doubly linked list and not a singly linked one?

Why does each list node store its key as well as its value?

Does get count as a use?